Lesson 9 of 20
Classes & Objects
Classes and Objects
A class is a blueprint; an object is an instance of that blueprint.
class Dog {
String name; // field
int age;
Dog(String name, int age) { // constructor
this.name = name;
this.age = age;
}
String bark() {
return name + " says: Woof!";
}
@Override
public String toString() {
return "Dog(" + name + ", age=" + age + ")";
}
}
Dog d = new Dog("Rex", 3);
System.out.println(d); // Dog(Rex, age=3)
System.out.println(d.bark()); // Rex says: Woof!
Encapsulation
Use private to hide fields and expose them through methods:
private double balance;
void deposit(double amount) { balance += amount; }
double getBalance() { return balance; }
Your Task
Create a BankAccount class (as a static inner class) with:
private String owner,private double balance- Constructor
BankAccount(String owner, double initialBalance) void deposit(double amount)boolean withdraw(double amount)— returnsfalseif insufficient funds, otherwise deducts and returnstruetoString()returning"<owner>: $<balance>"
Then run the sequence shown in the expected output.
TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.