Classes and objects
A class is a blueprint. Each new creates a separate object with its own copy of the fields.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
The class describes what every account has (fields) and can do (methods). Objects are the actual accounts. A method call runs the shared code against one particular object, available inside the method as "this".
Code
var a = new Account("Asha");
var b = new Account("Ravi");
a.Deposit(500);
b.Deposit(120);
Console.WriteLine(a.Balance + " " + b.Balance); // 500 120
class Account {
public string Owner;
public decimal Balance;
public Account(string owner) { Owner = owner; }
public void Deposit(decimal amount) { Balance += amount; }
}class Account {
String owner;
double balance;
Account(String owner) { this.owner = owner; }
void deposit(double amount) { balance += amount; }
}
public class Main {
public static void main(String[] args) {
Account a = new Account("Asha");
Account b = new Account("Ravi");
a.deposit(500);
b.deposit(120);
System.out.println(a.balance + " " + b.balance); // 500.0 120.0
}
}class Account {
public:
string owner;
double balance = 0;
Account(string owner) : owner(owner) {}
void deposit(double amount) { balance += amount; }
};
int main() {
Account a("Asha");
Account b("Ravi");
a.deposit(500);
b.deposit(120);
cout << a.balance << " " << b.balance << "\n"; // 500 120
}class Account:
def __init__(self, owner: str):
self.owner = owner; self.balance = 0
def deposit(self, amount: float) -> None:
self.balance += amount
a = Account("Asha")
b = Account("Ravi")
a.deposit(500)
b.deposit(120)
print(a.balance, b.balance) # 500 120Tips
- Fields you do not set start at their default: 0 for numbers, null for references, false for bool.
- Two variables can refer to the same object. Two new calls always give two different objects.
In the .NET library
Since C# 9, new() can omit the type when it is known: Account a = new("Asha"). Object initialisers set properties in the same statement: new Account("Asha") { Balance = 100 }.