tags:

views:

53

answers:

4
public class A
{  }

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

Now here if we call add in following way hen it gives an error: A a1 = new B; a1.add();

But when we add the add() method in class A and then call in the similar fashion then add() method of child class is called.

i.e.

public class A
{
  public void add()
  {
   System.out.println("add in A");
  }
}

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

call:

A a1 = new B;
a1.add();

output:

add in B

Why is it so?

A: 

Because java does not know at compile time that a1 will refer to an instance of B at runtime. It only knows the declared type, so it only allows calls that work with the declared type.

sepp2k
+2  A: 

at the method invocation of a1.add() the compiler checks if the method is present. But it only knows that a1 is a reference to an object of class A, which does not have that method. So the compilation fails.

In this trivial example it would probably be easy for the compiler to deduct the correct type. But in more general cases it wouldn't. And therefore this kind of logic is not part of the specs.

Jens Schauder
A: 

When the Java compiler looks at the reference a1, it knows what methods are available. In your first example, class A does not have add() in its API. It is legal in this case to perform a cast of a1 to B like so:

((B)a1).add();

and the compiler will not complain.

akf
A: 

You want to call a method on an object of declared type A but implement it only in a subclass B of A. In this situation you would normally make A an abstract class and declare add() an abstract method in A.

starblue