Instance Members → non-static members
Instance variables and methods belong to individual instances of a class. Each object has its own set of instance members that may have different values.
public class BankAccount {
int total;
public void getTotal() {
System.out.println(total);
}
}
BankAccount accountOne = new BankAccount();
BankAccount accountTwo = new BankAccount();
accountOne.total = 30; // Instance variable
accountTwo.total = 60;
accountOne.getTotal(); // Outputs 30
accountTwo.getTotal(); // Outputs 60
thisthis is a keyword used to refer to the current instance of a class.public class Car {
String color;
public Car(String color) {
this.color = color; // "this.color" refers to the instance field, not the parameter
}
}
Static variables and methods belong to the class itself, not to any instance. All objects share the same static members.
Static members are shared across all instances of a class.
public class Car {
static int numberOfCars;
public Car() {
numberOfCars++;
}
}
Car carOne = new Car();
Car carTwo = new Car();
System.out.println(Car.numberOfCars); // Outputs 2
this, because they are not associated with any instance.