Hi friends ! This is my first post in P2P Wrox ! I know VB6 but very new to Java (and OOP).
In the following code, I've created a super class (
MySuper) that has a subclass (
MySub1).
objSuper is reference of MySuper
objSub1 is a object of MySub1
Both the classes has a method
x(). Naturally the method is over ridden in MySub. MySub also has another method
y().
Now if I comment the
objSuper.y(); line, the code compiles perfectly. But with that line I'm gettin a compile error "cannot find symbol method y()".
I'm reading
Just Java 2 (6th Ed) by Pere van der Linden. In the summary of Chapter 8 he wrote "
superclass = subclass // always valid"
But then why this code is not working ? I'm really confused.
Please help me. Thanks in advance ! :)
Code:
public class Test
{
public static void main(String [] args)
{
MySuper objSuper;
MySub1 objSub1 = new MySub1();
objSuper = objSub1;
// x() is overridden, y() is NOT overridden
objSuper.x(); // OK
objSuper.y(); // Compile ERROR - "cannot find symbol method y()"
}
}
//---------------------------------------------------
class MySuper
{
public void x()
{
System.out.println("In MySuper's x()");
}
}
//---------------------------------------------------
class MySub1 extends MySuper
{
public void x()
{
System.out.println("In MySub1's x()");
}
public void y()
{
System.out.println("In MySub1's y()");
}
}