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

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)

Thanks James ...!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.