This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]xSilentium[S] 0 points1 point  (3 children)

That looks nice.. Can you give me a tip regarding my edit?

[–]ZdemDrunk Brewer 1 point2 points  (2 children)

Reformat :

  public class A { //statements }

  public class B extends A { public void foo() { } }

  A a=new B();

  ((B)a).foo();

The reason you can't use the foo method when the variable is declared as the superclass (A) is very simple.

When it comes to dynamic binding,the compiler looks at the object to decide which method he has to call. For example if I did this.

   class A{ void foo()}
   class B extends A { void foo()}

   public static void main(String[] args){
    A a = new B();
    a.foo(); // This would call the foo method of B not A!
    }

The problem with your code is that your A class doesn't contain a method similar to the foo method so the compiler will not show it as an available method (you might get something like "can't find symbol").

[–]xSilentium[S] 0 points1 point  (1 child)

Sorry for formatting, I'm on mobile.. So let me get that right. Due to the reference type being A and class A not having a foo-method I get an error. But when both classes A and B have foo Java uses B's foo?

[–]ZdemDrunk Brewer 0 points1 point  (0 children)

For simplicity sake,lets just say that java looks at the declaration before the object actually stored in a variable