Hi Team,
I have written a Sample Code in which I cast SubClass reference to point to SuperClass Object. It behaves like a SuperClass reference ( I mean when i try to use Methods which are not in SuperClass,it throws error so it means it is an instance of superclass) . But when i use the instance to operate on a SuperClass Method it outputs the value of overridden Subclass Method.
** I Expect the output like this "Playing BillieJean" but i get "Playing SmoothCriminal"
Here is code of superclass and subclass
public class SuperClass {
public void playMusic(){
System.out.println("Playing BillieJean");
}
public static void main(String[] args) {
SuperClass ref = new SuperClass();
}
}
** SUBCLASS
public class SubClass extends SuperClass{
public void playMusic(){
System.out.println("Playing smoothCriminal");
}
public void playMusic(String s){
System.out.println("playing they dont care about us");
}
public static void main(String[] args) {
SuperClass object1 = new SubClass();
SuperClass object2 = new SuperClass();
SubClass objectx = new SubClass();
SuperClass objecty = (SuperClass)objectx;
//SubClass object3 = (SubClass)object2;
objecty.playMusic();
}
}
** output
Playing SmoothCriminal