Instance Members & Static Members

invisibleufo101·2024년 9월 14일

Java

목록 보기
6/10
post-thumbnail

Instance Members → non-static members

Instance Variables & Methods (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
  • Instance members require an instance of the class to access and modify variables or methods.

Keyword: this

  • this is a keyword used to refer to the current instance of a class.
  • Useful when a method’s parameter has the same name as an instance field.
public class Car {
    String color;

    public Car(String color) {
        this.color = color;  // "this.color" refers to the instance field, not the parameter
    }
}

Static Variables & Methods (Members)

  • 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

Things to consider when using static members

  • Static methods cannot use instance fields or methods.
  • Static methods cannot access the keyword this, because they are not associated with any instance.
profile
하나씩 차근차근

0개의 댓글