이 경우 'x'라는 고유 한 정적 변수가있는 몇 개의 하위 클래스가 있습니다. 모든 하위 클래스는 정적 var를 같은 방식으로 사용하므로 코드 중복을 줄이고 수퍼 클래스에 기능을 추가하려고합니다. 이 경우에는 수퍼 클래스에서 'getX'메소드가 사용됩니다. 여기에서 x 값을 반환하고 싶습니다. 지금은 슈퍼 클래스의 x 값을 사용하고 자식 클래스의 값을 사용하지 않는다는 문제에 직면하고 있습니다. 수퍼 클래스에서 하위 클래스의 x 값에 액세스하려면 어떻게해야합니까?Java | 부모 클래스와 자식 클래스의 정적 변수 | 부모 클래스에서 자식 var 값에 액세스
public class Playground {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
Child1 child1 = new Child1();
System.out.println("Parent.x " + parent.x);
System.out.println("child.x " + child.x);
System.out.println("child.x " + child1.x);
System.out.println("get x: " + parent.getX());
System.out.println("get x: " + child.getX());
}
}
class Parent {
static String x = "static of parent";
String y = "instance of parent";
String getX() {
return x;
}
}
class Child extends Parent {
static String x = "static of child";
String y = "instance of child";
}
class Child1 extends Parent {
static String x = "static of child1";
String y = "instance of child";
}
이 코드를 출력합니다 : Parent.x static of parent child.x static of child child.x static of child1 get x: static of parent get x: static of parent
< - 여기에 아이의 정적한다
희망 누군가가 나에게 도움이 될 수 있습니다.
환호
질문이있는 경우에는
그냥 물어, 그래서 모든 하위에 3-4 방법 (실제 시나리오에서)입니다 getX를 복사하지 않습니다 classes –그러나 getX 메소드를 호출하면 java가 Parent에서 메소드를 호출합니다. 그것이 부모에게서 x를 얻는 이유입니다. 예상 된 결과를 얻는 유일한 방법이라고 생각합니다. –