수업소개
static 키워드에 대해서 살펴보는 수업입니다.
강의
소스코드
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 28 29 30 31 32 33 34 35 36 | class Foo{ public static String classVar = "I class var" ; public String instanceVar = "I instance var" ; public static void classMethod() { System.out.println(classVar); // Ok // System.out.println(instanceVar); // Error } public void instanceMethod() { System.out.println(classVar); // Ok System.out.println(instanceVar); // Ok } } 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" ; System.out.println(Foo.classVar); // changed by f1 System.out.println(f2.classVar); // changed by f1 // f1.instanceVar = "changed by f1" ; System.out.println(f1.instanceVar); // changed by f1 System.out.println(f2.instanceVar); // I instance var } } |