Concept Flow - Instance methods
Create Object
Call Instance Method
Method Uses Object's Data
Method Executes and Returns
Back to Caller
An instance method is called on an object, uses that object's data, runs its code, then returns control back.
Jump into concepts and practice - no test required
class Dog { String name; void bark() { System.out.println(name + " says Woof!"); } } public class Main { public static void main(String[] args) { Dog d = new Dog(); d.name = "Buddy"; d.bark(); } }
| Step | Action | Object State (name) | Output |
|---|---|---|---|
| 1 | Create Dog object d | null | |
| 2 | Set d.name = "Buddy" | Buddy | |
| 3 | Call d.bark() | Buddy | Buddy says Woof! |
| 4 | Method bark() finishes | Buddy |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| d.name | null | null | Buddy | Buddy | Buddy |
Instance methods belong to objects. They use the object's data (fields). Called with object.methodName(). Can access and modify object state. Return control after execution.
instance methods in Java?this to refer to the current object.display() of an object obj?obj.display();.static display(); is invalid syntax.class Car {
String model;
void setModel(String m) {
model = m;
}
void printModel() {
System.out.println(model);
}
}
public class Test {
public static void main(String[] args) {
Car c = new Car();
c.setModel("Tesla");
c.printModel();
}
}c calls setModel("Tesla"), which sets the instance variable model to "Tesla".printModel() prints the current value of model, which is "Tesla".class Person {
String name;
void setName(String name) {
name = name;
}
void printName() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
p.printName();
}
}name = name; assigns the parameter to itself, not to the instance variable.name is not set, printName() prints null.BankAccount with an instance method deposit that adds money to the account balance, and another method getBalance that returns the current balance. Which code correctly implements these instance methods?balance and instance methods that correctly update and return it.amount.