2016-08-15 2 views
-4

superCi 필드에 아무런 영향을 미치지 않으십니까? 출력이 012이지만, 클래스가 C을 확장하기 때문에 321이 아닌 이유는 무엇입니까?분야 용 자바 슈퍼

public class C { 
     protected int i; 

     public C(int i){ 
      this(i,i); 
      System.out.print(this.i); 
      this.i=i; 
     } 

     public C(int i, int j) { 
      System.out.print(this.i); 
      this.i=i+j; 
     } 

     public C(){ 
       this(1); 
       System.out.print(i); 
     } 

     public static void main(String[] args) { 
      C c=new C(); 
     } 
} 

public class B extends C{ 
     public B(){ 
       super.i=3; 
     } 



     public static void main(String[] args){ 
      C c=new B(); 
     } 
} 
+2

이 nesseccary 정말에서 super.testMethod() 전화 방법 testMethod을 수행하여 단지 다른 제목으로 질문을 여러 번 게시 할 수 있을까? –

+0

오늘 같은 질문이 –

+0

@Andreas : 글쎄, 그건 같은 질문이 아니에요, 그것은 후속 조치입니다. – Thilo

답변

1

super은 재정의 된 메소드에 액세스하는 데 사용할 수 있습니다. 시나리오에서 i은 B의 상속 된 멤버입니다.

C에서 정의 된 B에서 메서드를 재정의하는 경우 super 키워드를 사용하여 B에서 호출 할 수 있습니다. 클래스 Bi의 자체 버전을 선언하지 않기 때문에

+1

"사용 가능"또는 "사용 중"으로 변경하는 것이 "사용됩니다"라고 생각하십시오. – Bathsheba

2

super.ithis.i (또는 단순히 i)을 의미한다, 그래서 그것은 이미 C에서 필드를 상속합니다.

public B(){ 
      super.i=3; // the super here does not do anything 
    } 

생성자가해야하는 첫 번째 작업은 수퍼 생성자 중 하나를 호출하는 것입니다. 당신이 i은 (는) 이전 값을 출력 이유 그 3. 설정되기 전에, 슈퍼 클래스 C의 코드가 실행됩니다 볼 수 있듯이

public B(){ 
      super(); 
      i=3; 
    } 

: 그래서이 동일합니다.

0

아주 간단합니다. 무슨 일이 일어나고있는 것은 이것이 :

B Constructor is called. 

B doesn´t have an explicit super constructor call- so implicity call super(). 

C() Constructor is called -> call C(int) 

C(int) Constructor is called -> call C(int,int); 

C(int, int) is called. print i. i only has the default value yet so print ->0 

C(int, int) does increment i by j, which at this point is 1+1 = 2 

C(int) Constructor callback, as C(int, int) is done, print i = 2 

C(int) sets i = 1 and prints i = 1. 

B() callback as C() is done. set instance variable i to 3. 

당신이 021 같이 일어날 않는 모든 것은 이것이 다른 출력을 볼 수 있듯이.

귀하의 초기 의도는 무엇인지 모르지만 super은 다른 의미를 가질 수 있습니다.

생성자에서 보통 부모 생성자에 super으로 액세스합니다.

super.i하여 부모 클래스의 인스턴스 변수 i에만 액세스합니다.

당신은에 ParentClass