본문 바로가기
자바(Java)/자바 클래스

[Java Class.04] Member of Instance & Static

by 긱펀 2024. 2. 23.
반응형

[Java Class.04] Member of Instance & Static

 

1.Instance member와 this

  • 인스턴스 멤버(Instance member)란 객체(인스턴스)를 생성한 후 사용할 수 있는 필드(Filed)와 메소드(Method)를 말한다.
  • 인스턴스 멤버는 객체에 소속된 멤버이기 때문에 객체 없이는 사용할 수 없다.

 

1.1.인스턴스 멤버 선언과 사용

public class Car {
  // Field
  String color;
  int price;

  // method
  void setColor(String color) {
    this.color = color; // this
  }
}

 

public class Main {
  public static void main(String[] args) {
    Car myCar = new Car();
    myCar.price = 1000;      // field 사용
    myCar.setColor = "red";  // method 사용
  }
}
  • 인스턴스 필드로 color, price를 선언했습니다.
  • 인스턴스 메소드로 setColor를 선언했습니다.
  • Main 함수에서 Car 객체를 만들고 인스턴스 필드와 메소드를 사용했습니다.
  • 인스턴스 멤버(필드&메소드)를 외부 클래스에서 사용하기 위해서는 객체(인스턴스)를 생성한 뒤 사용가능합니다.
  • this는 객체 내부에서 인스턴스 멤버에 접근하기 위해 사용합니다.
  • this는 객체 자신을 가리키는 의미 입니다.

 

1.2.Static member

  • Static(정적, 고정된) 멤버는 클래스에 고정된 멤버로서, 객체를 생성하지 않고 사용할 수 있는 멤버(필드&메소드)를 말합니다.
  • 이들을 각각 Static field, Static method라고 부릅니다.

 

public class Calculator {
  static double pi = 3.14; // static field
  String color;            // instance field
  
  static int plus(int x, int y) { // static method
    int result = x + y;
    return result;
  }

  void setColor(String color) { // instance method
    this.color = color;
  }
}

 

 

public class Main {
  public static void main(String[] args) {
    double r1 = 10 * 10 * Calculator.pi; // static field 사용
    int r2 = Calculator.plus(3, 5); // static method 사용

    System.out.println(r1);
    System.out.println(r2);

    Calculator myCal = new Calculator();
    string r3 = myCal.setColor("red"); // instance method 사용
    int r4 = myCal.plus(10, 5); // 객체만든 후 instance method 사용(권장x)
  }
}

 

  • 필드를 선언할 때 인스턴스 필드로 할 것인가, 아니면 정적 필드로 할 것인가를 판단해야 합니다.
  • 객체마다 모두 가지고 있어야 할 고유의 데이터라면 인스턴스 필드로 선언합니다.
  • 객체마다 모두 가지고 있을 필요가 없는 공용 데이터라면 정적 필드로 선언하는 것이 좋습니다.
  • 정적 필드와 정적 메소드는 원칙적으로 클래스 이름으로 접근해야 하지만, 객체를 만든 후 객체로도 접근이 가능합니다.
  • 하지만 정적 요소는 클래스 이름으로 접근하는 것을 권장합니다.

 

1.3.Static method 선언 시 주의할 점

  • 정적 메소드(Static method)를 만들고 이 내부에 인스턴스 필드나 인스턴스 메소드, 그리고 this를 사용할 수 없다.
  • 그래서 아래와 같은 코드는 compile error가 발생한다.
public class ClassName {
  // instance field & method
  int field1;
  void method1 () { }

  //static field & method
  static int field2;
  static void method2() { }

  //static method
  static void method3() {
    this.field1 = 5; // (x) <= error
    this.method1(); // (x) <= error
    field2 = 0; // (O)
    method2(); // (O)
  }
}

 

  • 정적 메소드(Static method)에서 인스턴스 멤버를 사용하고 싶으면 아래와 같이 객체를 먼저 생성하고 접근해야 한다.
public class ClassName {
  // instance field & method
  int field1;
  void method1 () { }

  //static field & method
  static int field2;
  static void method2() { }

  //static method
  static void method3() {
    ClassName obj = new ClassName(); // make object
    obj.field1 = 5; // (O)
    obj.method1(); // (O)
  }
}

 

  • main() 메소드도 정적 메소드(static method)이므로 객체 생성 없이 인스턴스 멤버를 main() 메소드에서 사용할 수 없다.
public class Main {
  int speed;

  void go() {  }
  
  public static void main(String[] args) {
    speed = 10; // (x) <= error
    go(); // (x) <= error
  }
}

 

  • main() 메소드에서 객체를 만들어 인스턴스 멤버를 사용하는 올바른 예는 아래와 같다.
public class Main {
  int speed;

  void go() {  }
  
  public static void main(String[] args) {
    Main m = new Main();
    m.speed = 10; // (o)
    m.go(); // (o) 
    System.out.println("2");
  }
}

 

 

[유제1]

Consider the class Temperature below which has a static variable. What is the output of the main method below?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Main {
    public static void main(String[] args) {
        Temperature t1 = new Temperature(75);
        Temperature t2 = new Temperature(100);
        Temperature t3 = new Temperature(65);
        System.out.println("Max Temp: " + Temperature.maxTemp);
    }
}
 
class Temperature
{
    private int temperature;
    public static int maxTemp = 0;
 
    public Temperature(int t)
    {
        temperature = t;
        if (t > maxTemp)
        {
             maxTemp = t;
        }
    }
}
cs

 

A. Max Temp: 0

B. There is a compiler error because the static variable maxTemp cannot be used inside a non-static constructor.

C. Max Temp: 100

D. Max Temp: 75

E. Max Temp: 65

 

 

[유제2]

Fix the bugs in the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Main {
    public static void main(String[] args) {
        Temperature t1 = new Temperature(75);
        Temperature t2 = new Temperature(100);
        Temperature.printMax();
    }
}
 
class Temperature
{
    private double temperature;
    public static double maxTemp = 0;
 
    public Temperature(double t)
    {
        temperature = t;
        if (t > maxTemp)
        {
             maxTemp = t;
        }
    }
 
    public static printMax()
    {
        System.out.println(temperature);
    }
cs

 


[유제 정답은 아래 "더보기" 클릭]

더보기

[유제1 정답]

C

(maxTemp is initialized to 0 and then changed to 75 and then 100 by the constructor calls)

 

[유제2 정답]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Main {
    public static void main(String[] args) {
        Temperature t1 = new Temperature(75);
        Temperature t2 = new Temperature(100);
        Temperature.printMax();
    }
}
 
class Temperature
{
    private double temperature;
    public static double maxTemp = 0;
 
    public Temperature(double t)
    {
        temperature = t;
        if (t > maxTemp)
        {
             maxTemp = t;
        }
    }
 
    public static void printMax()
    {
        System.out.println(maxTemp);
    }
}
cs
728x90
반응형

댓글