简体   繁体   中英

Question about overwritten methods in classes that extend each other.

I'm studying for a Java-exam and have a question concerning static and dynamic types.

I've got 4 classes: A, B, C and Main.

public class A {
   private void tell(){
   System.out.println("AA");
    }
}

public class B extends A {
public void tell(){
    System.out.println("BB");
}
}

public class C extends B {

}

public class Main{
public static void main(String[] args) {
    A c = new C();       
    c.tell();
}

}

My suggestion was: the output should be "BB", because c has the dynamic type C. Since C doesn't have the method "tell" the method of the upper class B is used, which prints "BB".

The outcome however is an error, because Java looks for "tell" in A. In A it of course can't find it, because there it is declared priavte. But why does it look in A, although only it's static type is A, but it's dynamic type is C?

You are getting an error because at compile time, the compiler does not know the actual instance that will be put in A, so when the compiler sees c.tell() he only looks at the class A which indeed does not have an acessible tell() method.

One way to understand this is with this example:

public class A {
  private void tell(){
      System.out.println("AA");
  }
}

public class B extends A {
  public void tell(){
      System.out.println("BB");
  }
}

public class C extends A {

}

public class Main{
  public static void main(String[] args) {
      A b = new B();      
      b.tell();
      A c = new C();       
      c.tell();
  }

}

You can see that the first 2 lines would be ok (by your current logic of thinking). B has the method tell() so b should be able to call tell() . But using the exact same assignment with another subclass of C which does not have the tell() method then your logic would fail. A nor C have the tell() method so the program suddenly has a call to a method that does not exist or is not accessible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM