Repository navigation
More Object Oriented Programming
Polymorphism
Polymorphism is defined as “Same Code” giving “Different Behavior”. Let’s look at an example. Let’s define an Animal class with a method shout. public class Animal { public String shout() { return "Don't Know!"; } } Let’s create two new sub classes of Animal overriding the existing shout method in Animal. class Cat extends Animal { public String shout() { return "Meow Meow"; } } class Dog extends Animal { public String shout() { return "BOW BOW"; } public void run(){ } } Look at the code below. An instance of Animal class is created. shout method is called. Animal animal1 = new Animal(); System.out.println( animal1.shout()); //Don't Know! Look at the code below. An instance of Dog class is created and store in a reference variable of type Animal. Animal animal2 = new Dog(); //Reference variable type => Animal //Object referred to => Dog //Dog's bark method is called. System.out.println( animal2.shout()); //BOW BOW When shout method is called on animal2, it invokes the shout method in Dog class (type of the object pointed to by reference variable animal2). Even though dog has a method run, it cannot be invoked using super class reference variable. //animal2.run();//COMPILE ERROR
instanceof operator checks if an object is of a particular type. Let us consider the following class and interface declarations: class SuperClass { }; class SubClass extends SuperClass { }; interface Interface { }; class SuperClassImplementingInteface implements Interface { }; class SubClass2 extends SuperClassImplementingInteface { }; class SomeOtherClass { }; Let’s consider the code below. We create a few instances of the classes declared above. SubClass subClass = new SubClass(); Object subClassObj = new SubClass(); SubClass2 subClass2 = new SubClass2(); SomeOtherClass someOtherClass = new SomeOtherClass(); Let’s now run instanceof operator on the different instances created earlier. System.out.println(subClass instanceof SubClass);//true System.out.println(subClass instanceof SuperClass);//true System.out.println(subClassObj instanceof SuperClass);//true System.out.println(subClass2 instanceof SuperClassImplementingInteface);//true instanceof can be used with interfaces as well. Since Super Class implements the interface, below code prints true. System.out.println(subClass2 instanceof Interface);//true If the type compared is unrelated to the object, a compilation error occurs. //System.out.println(subClass // instanceof SomeOtherClass);//Compiler Error Object referred by subClassObj(SubClass)- NOT of type SomeOtherClass System.out.println(subClassObj instanceof SomeOtherClass);//false