Here is a short example of casting a child class to a parent, and then calling a method.
I expected the foo method to get called in the child class, not the parent class. But, I am getting a compile error saying that the parent class doesn't have this method.
Why does Java care whether the parent class has it, if I'm only calling it on the child class?
public static void main(String[] args)
{
A a = new A();
B b = new B();
b.foo(1, 2, 3); // Ok
((A) b).foo(1, 2); // Also ok.
// Prints "In foo(int, int) method of class B"
((A) b).foo(1, 2, 3); // Will not compile
}
// later in the code...
class A
{
public int foo(int a, int b)
{
System.out.println("In foo(int, int) method of class A");
return 1;
}
}
class B extends A
{
public int foo(int a, int b)
{
System.out.println("In foo(int, int) method of class B");
return 0;
}
public int foo(int a, int b, int c)
{
System.out.println("In foo(int, int, int) method of class B");
return -1;
}
}