Behavior
Problem
Everyone withdraws their own way
The bank has an Account class with an owner and a balance. Money is withdrawn in two places in the program. The ATM checks that there is enough money. The card payment was written by someone else, and it does not check:
Account account = new Account("Maria", 100);
// The ATM checks that there is enough money.if (account.Balance >= 70){ account.Balance -= 70;}
// Someone else wrote the card payment. It has no check.account.Balance -= 50;
Console.WriteLine(account.Balance);-20The account is below zero. The rule "you cannot withdraw more than you have" is important, but it is written (or forgotten) separately in every place that withdraws.
The idea
Methods live with the data
The withdrawal logic is part of the account, so put it in the Account class. A method in the class, without static, is an instance method:
class Account{ public string Owner; public double Balance;
public Account(string owner, double balance) { Owner = owner; Balance = balance; }
public void Deposit(double amount) { Balance += amount; }
public void Withdraw(double amount) { if (amount <= Balance) { Balance -= amount; } else { Console.WriteLine("Not enough money: " + Owner); } }}
class Program{ static void Main() { Account account = new Account("Maria", 100); account.Withdraw(70); account.Withdraw(50); account.Deposit(20); Console.WriteLine(account.Balance); }}Not enough money: Maria50- You call the method on an object with a dot:
account.Withdraw(70), just like the fields. - Inside,
Balanceis the balance of this account, the object before the dot. You can also writethis.Balance. - The check is written once. Anyone who withdraws through the method goes through it.
Account maria = new Account("Maria", 100);Account peter = new Account("Peter", 40);maria.Withdraw(70);peter.Withdraw(70);Console.WriteLine(maria.Balance + " " + peter.Balance);Step by step, in words
- Two accounts, two objects. Each one has its own balance.
- maria.Withdraw(70): this gets an arrow to the object before the dot.
- In the method, the balance belongs to this: 100 - 70 = 30.
- Same method, different object: now this points to Peter.
- 70 is more than 40: the method prints a refusal, and Peter's balance stays the same.
- There is one copy of the method code. The fields belong to the object you call it on.
The card payment can no longer "forget" the check if it withdraws with Withdraw. It can still write straight into the field, though. You will see how to stop that in the "Encapsulation" lesson.
The idea
Instance method or static method
The methods from the "Methods" module were static. They get everything as parameters and have no object of their own. An instance method works with the fields of the object it was called on:
static double ApplyDiscount(double price, double percent){ return price * (100 - percent) / 100;}
double price = ApplyDiscount(10, 10);account.Withdraw(70);You cannot call an instance method through the class name. It is not clear which account to withdraw from:
Account.Withdraw(70);error CS0120: An object reference is required for the non-static field, method, or property 'Account.Withdraw(double)'What exactly static means and when you need it comes in the lesson "static: what all objects share".
Try it
Whose account?
What will the program print?
Account maria = new Account("Maria", 100);Account peter = new Account("Peter", 40);maria.Deposit(30);peter.Withdraw(10);Console.WriteLine(maria.Balance + " " + peter.Balance);Each object has its own balance. maria.Deposit(30) changes only Maria's balance, and peter.Withdraw(10) changes only Peter's. Peter has 40, so withdrawing 10 goes through.
Try it
Find the bug
Pick the line with the bug.
static before the method means it has no object. Then there is also no balance for it to see. The compiler stops on the line with the balance:
error CS0120: An object reference is required for the non-static field, method, or property 'Account.Balance'But the bug is in the method header: remove static.
The idea
A method can also answer
An instance method can return a result, just like the methods from the "Methods" module. A product knows its price and quantity, so it can tell you its own cost:
class Product{ // the fields and the constructor, as before
public double Total() { return Price * Quantity; }}
Product[] cart ={ new Product("Bread", 1.20, 2), new Product("Milk", 2.10, 1), new Product("Coffee", 7.50, 1)};double sum = 0;foreach (Product p in cart){ sum += p.Total();}Console.WriteLine("Total: €" + sum);Total: €12Compare this with the first lesson of the module: there, the sum was computed in Main from the fields. Now Main only asks each product. If a bulk discount is added tomorrow, you change only Total().
The idea
What does the object look like as text?
If you print a product directly, you get something useless:
Product coffee = new Product("Coffee", 7.50, 1);Console.WriteLine(coffee);ProductC# prints only the class name.
The class can say how it should be shown. The method is called ToString(), and it returns text:
class Product{ // the fields and the constructor, as before
public double Total() { return Price * Quantity; }
public override string ToString() { return Name + " x" + Quantity + ": €" + Total(); }}
Product coffee = new Product("Coffee", 7.50, 1);Product bread = new Product("Bread", 1.20, 2);Console.WriteLine(coffee);Console.WriteLine("In the cart: " + bread);Coffee x1: €7.5In the cart: Bread x2: €2.4You do not call it yourself. Console.WriteLine(coffee) and "In the cart: " + bread call it for you when the object has to become text.
For now, write override in the header exactly like this. What it means comes in the "Inheritance and polymorphism" module.
Try it
A book in a sentence
What will the program print?
class Book{ public string Title; public string Author;
public Book(string title, string author) { Title = title; Author = author; }
public override string ToString() { return Title + " by " + Author; }}
Book book = new Book("Tobacco", "Dimitar Dimov");Console.WriteLine("Reading: " + book);"Reading: " + book has to turn book into text. So the book's ToString() is called, and it returns the title and the author.Exercise
Objects that do something
Solve the tasks in your editor. Take the classes from the earlier lessons and add methods to them.
Person: a methodIntroduce()that prints the name and the age.SimpleCar: a methodAccelerate()that increases the speed by 10. Now Main does not touch the speed directly.DanceMove: a methodPerform()that "performs" the move.Book: a methodRead()that prints "Reading [title] by [author]".
Create one object of each class and call its methods:
Hi, I'm Maria and I'm 34 years old.Speed after accelerating: 10Performing moonwalk for 5 secondsReading Under the Yoke by Ivan VazovExercise
A car with fuel
A Car class with a brand, a speed, fuel (in liters) and a mileage in kilometers. The constructor gets the brand and the fuel. The speed and the mileage start at 0.
Accelerate()increases the speed by 10.Refuel(double liters)adds fuel, but the tank holds at most 50 liters.Drive(int distance)uses 6 liters per 100 km and adds the distance to the mileage. If there is not enough fuel, it prints a message and the car does not move.ToString()returns the brand, the mileage and the fuel.
Car car = new Car("Toyota", 20);car.Accelerate();car.Accelerate();Console.WriteLine("Speed: " + car.Speed);car.Drive(100);Console.WriteLine(car);car.Drive(300);car.Refuel(40);Console.WriteLine(car);car.Drive(300);Console.WriteLine(car);Speed: 20Toyota: 100 km, 14 LNot enough fuel for 300 kmToyota: 100 km, 50 LToyota: 400 km, 32 Ldistance * 6 / 100.0. With 100 instead of 100.0, the division is integer division, and for 30 km you get 1 liter instead of 1.8.More tasks
- Discount. Add a method
ApplyDiscount(double percent)toProductthat lowers the price of the product. Compare it with the static method from the "Methods" module that returned a new price. - An account with a history. Add an operation counter to
Account: every deposit and every successful withdrawal increases it by 1. A methodToString()returns the owner, the balance and the number of operations.
Test