2017-01-06 5 views
2

이 경우 '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< - 여기에 아이의 정적한다

희망 누군가가 나에게 도움이 될 수 있습니다.

환호

답변

2

자식에게 getX 메서드를 추가해보십시오. 이렇게 :

class Child extends Parent { 
    static String x = "static of child"; 
    String y = "instance of child"; 
    String getX() { 
     return x; 
    } 
} 
+0

질문이있는 경우에는

Parent.x static of parent child.x static of child child.x static of child1 get x: static of parent get x: static of child 
그냥 물어, 그래서 모든 하위에 3-4 방법 (실제 시나리오에서)입니다 getX를 복사하지 않습니다 classes –

+0

그러나 getX 메소드를 호출하면 java가 Parent에서 메소드를 호출합니다. 그것이 부모에게서 x를 얻는 이유입니다. 예상 된 결과를 얻는 유일한 방법이라고 생각합니다. –

1

하위 클래스에 getX 메소드를 추가하십시오. 부모 getX 메서드는 부모 클래스의 정적 변수를 가리 킵니다.

1

은 당신이하려고하는 것은 기본 OOP 원칙/encapulation을 숨기고 정보의 위반입니다.

다른 클래스는 클래스를 저장 또는 속성 (일명 변수 또는 필드)를 처리하는 방법에 대해 알고 없습니다. 이 클래스 갖는 데이터 전송 객체 (DTO)를 (거의) 나타내는 경우 clases가 게터 이러한 규칙의 예외가

(@ RosárioPereiraFernandes 의해 제안) 세터이없는 것을 포함 비즈니스 로직이없고 단지 구조화 된 데이터에 액세스 할 수 있습니다. DTO는 게터 및 (덜 자주) 세터이 있어야합니다.

다른 클래스는 내부 상태 (자신의 멤버 변수의 값)을 수정하기 위해 관련 및 비즈니스 이름과 방법을 제공한다 :

class Car{ 
    private final int maxSpeedInMph = 100; 
    private int speedInMph = 0; 
    public void accellerateBy(int speedDiffInMph){ 
    if(maxSpeedInMph >=speedInMph + speedDiffInMph) 
     speedInMph += speedDiffInMph; 
    else 
     speedInMph = maxSpeedInMph ; 
    }  
    public void accellerateTo(int newSpeedInMph){ 
    if(maxSpeedInMph >= newSpeedInMph) 
     speedInMph = newSpeedInMph; 
    else 
     speedInMph = maxSpeedInMph ; 
    } 
    public void decellerateBy(int speedDiffInMph){ 
    if(0<=speedInMph - speedDiffInMph) 
     speedInMph += speedDiffInMph; 
    else 
     speedInMph = 0; 
    } 
    public void emengencyBreak(){ 
    speedInMph = 0; 
    } 
    // you get the idea? 
} 
+0

나는 그것을 얻는다, 나는 나의 경우마다 각 아이는 내가 사용하고 싶은 독특한 상수를 가지고있다. 조작이 없습니다. 여러 유형의 BankAccount를 가진 은행에 대해 생각해보십시오. 각 유형의 BankAccount에는 일정한 BankFee가 있습니다. 그래서 각 BankAccount에 가지 않고 BankFee 유형을 리턴하는 getter를 추가하지 않고 각 BankAccount에 대해 BankFee를 리턴하는 메소드를 갖고 싶습니다. –

+0

@ DΦC__WTF : * "나는 각 어린이에게 내가 사용하고 싶은 독특한 상수를 가지고있다"* 왜? - 대부분 'swich'문장에서 사용할 계획입니다. 그러나 클래스 유형을 기반으로 특정 동작을 수행하려면 * 다형성 *을 사용해야합니다. –

1

용액 상위에 고정되어 있지 할 수 있지만, 인스턴스가 있었다 들.

class Parent{ 
    private final X x 
    public Parent(X x){ 
     this.x = x; 
    } 

    public X getX() { 
     return x; 
    } 
} 

그런 다음 당신의 아이에, 당신은 여전히 ​​정적을 가질 수 있지만, 나는 부모로부터 아이 변수에 액세스 할 수 없습니다 알다시피 당신은

class Child extends Parent { 
    static final X x = .... 
    public Child() { 
     super(x); 
    } 
} 
1

지금까지 생성자에 건네 -수업.

하지만 당신은 자식 클래스에 String getX()을 무시할 수

@Override 
protected String getX() {   
    return x; 
} 

그리고 자바는 "가장 낮은"getX() 방법을 호출


내가 다른 귀하의 예제 코드를 것

:

public class Playground { 

private static Parent parent = new Parent("static of parent"); 
private static Child child = new Child("static of child"); 
private static Child1 child1 = new Child1("static of child1"); 

    public class Playground { 

private static Parent parent = new Parent("static of parent"); 
private static Child child = new Child("static of child"); 
private static Child child1 = new Child("static of child1"); 

    public static void main(String[] args) { 


    System.out.println("Parent.x " + parent.getX()); 
    System.out.println("child.x " + child.getX()); 
    System.out.println("child.x " + child1.getX()); 

    System.out.println("get x: " + parent.getX()); 
    System.out.println("get x: " + child.getX()); 
    } 
} 

class Parent { 
    private String x; 
    public Parent(String x) { 
     this.x = x; 

    } 

    public String getX() { 
      return this.x; 
     } 
} 

class Child extends Parent { 
    protected Child(String x) { 
     super(x); 
    } 
} 

을 -> 다음 출력이 표시됩니다 :당신은 내가 6 개 서브 클래스가 내 진짜 시나리오에서