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();




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;




** output

Playing SmoothCriminal

4 Years
Discussion Span
Last Post by murali2489

Java binds instance methods at run time, so when it executes objecty.playMusic(); it looks at the actual object that refers to, and uses its methods as appropriate. The type of the reference vaiable is not relevant at run time, it's just used at compile time to ensure that any object referred to by that variabke will have a playMusic() method.

(static methods, on the other hand, are bound at compile time)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.