1. 인스턴스
클래스 내의 메서드는 필요할 때마다 쓰면 되는 일회용 기능 같은 것.
근데 인스턴스는 뭔가 일시적인 게 아니라, 새로운 복제본 그 자체의 맥락을 계속 이어갈 수 있다.
일회용으로 작업을 끝내면 되는 것들은 메서드나 변수를 클래스에 있는 그대로 이용하지만,
긴 맥락으로 작업해야 하는 경우에는 클래스를 직접 사용하지 않고, 복제본을 만들어서 이용하는 것이다.
선언하는 방법:
" 클래스 이름" "인스턴스 이름" = new "클래스 이름"();
예시:
Print p1 = new Print();
class Print{
public String delimiter = "";
public void A() {
System.out.println(delimiter);
System.out.println("A");
System.out.println("A");
}
public void B() {
System.out.println(delimiter);
System.out.println("B");
System.out.println("B");
}
}
public class Sample8 {
public static void main(String[] args) {
Print p1 = new Print();
p1.delimiter = "----";
p1.A();
p1.A();
p1.B();
p1.B();
Print p2 = new Print();
p2.delimiter = "****";
p2.A();
p2.A();
p2.B();
p2.B();
p1.A();
p2.A();
p1.A();
p2.A();
}
}
2. static
스태틱은 클래스 소속, 스태틱이 없는 것은 인스턴스 소속이라는 것을 기억하자.
1. 인스턴스들은 classVar랑 연결되어 있음. 한 인스턴스의 classVar를 변경하면 클래스의classVar, 그리고 같은 클래스에 있는 다른 instance의 값도 같이 변경된다.
2. 각각의 instance 변수들( static 없는 것 )은 완전히 독립적이고, 자기 instance안에서만 뭔가 변하게 할 수 있음.
class Foo{
public static String classVar = "I class var";
public String instanceVar = "I instance var";
public static void classMethod() {
System.out.println(classVar);
//System.out.println(instanceVar); //Error. 클래스 메소드 안에서 인스턴스 변수에 접근 불가.
}
public void instanceMethod() {
System.out.println(classVar);
System.out.println(instanceVar); //인스턴스 메소드 안에서는 인스턴스 변수에도 접근 가능함.
}
}
public class StaticApp {
public static void main(String[] args) {
System.out.println(Foo.classVar); //OK
//System.out.println(Foo,instanceVar); //Error
Foo.classMethod();
//Foo.instanceMethod(); //인스턴스 메소드이기 때문에 클래스를 통해 접근할 수 없음.
Foo f1 = new Foo();
Foo f2 = new Foo();
System.out.println(f1.classVar); // I class var
System.out.println(f1.instanceVar); // I instance var
f1.classVar = "changed by f1"; // f1 인스턴스의 classVar 를 변경했을 때
System.out.println(Foo.classVar); // class Foo의 classVar 변수도 변경됨. changed by f1
System.out.println(f2.classVar); // f2 인스턴스의 classVar 변수도 변경됨. changed by f1
f1.instanceVar = "changed by f1"; // f1 인스턴스의 instanceVar를 변경했을 때
System.out.println(f1.instanceVar); // f1의 instanceVar 변수 변경됨. changed by f1
System.out.println(f2.instanceVar); // f2의 instanceVar는 변경 안 됨. 그대로 있음 == I instance bar
//System.out.println(Foo.instanceVar); //이런 건 존재 X
}
}
https://www.youtube.com/playlist?list=PLuHgQVnccGMAb-e41kXPSIpmoz1RvHyN4
JAVA 객체지향 프로그래밍
www.youtube.com
[출처: 생활코딩 - 유튜브 강좌]
'JAVA' 카테고리의 다른 글
[생활코딩] Java 메서드 강의 1-6 (1) | 2024.02.06 |
---|---|
[점프 투 자바] 객체 지향 프로그래밍 - 클래스, 메서드, 인스턴스 (1) | 2024.02.03 |
[생활코딩] Java의 객체지향 프로그래밍 - 클래스, 변수와 메소드 (0) | 2024.02.03 |
[점프 투 자바] for each 문 (1) | 2024.02.01 |
[점프 투 자바] for 문 (0) | 2024.02.01 |