The following code in java, when run on elipse, gives same output even if we replace
superclass s=new sub();
with,
sub s= n
I'm rewriting your code here with some modification. Please look at the changes.
public class superclass {
int num=2;
public static void main(String str[]){
superclass s=new sub();
//HERE: nothing changes if we write, sub s=new sub();
s.supermethod();
s.method();
}
...
...
//This method is not overridden.
void methodInSuper(){
System.out.prinln("method not overridden.");
}
}
class sub extends superclass{
int num=5;
...
...
//This is only in subclass.
void methodInSub(){
System.out.println("method only in subclass.");
}
}
Now when you are creating an object like this:
superclass s1=new sub();
Then you can call all the overridden methods like
s1.supermethod();
s1.method();
In this case the methods of subclass will be called.
you can also call methods of superclass those are not overridden like
s1.methodInsuper();
but if you try to access method defined only in subclass like
s1.methodInsub();
then it will be a compile time error.
It is becoz s1 is of type Superclass.
If you still want to call the method in subclass then you need to typecast s1 to subclass like
Sub s = (Sub) s1;
After that you can call the method of the subclass.
And if you create an object like
Sub s2 = new Sub();
Then you can access any methods defined in subclass or superclass.
The earlier creation of object is basically used for implementing "Run Time Ploymorphism".
Hope you got your answer.