Polymorphism
- A concept that is made by the addition of Overriding, Inheritance, Casting is called Polymorphism.
Refer to this code sample,
class A {
void print (){
System.out.println ("A");
}
}
class B extends A{
void print (){
System.out.println ("B");
}
}
B b = new B () ;
b.print();
A a = new A () ;
a.print () ;
A a1 = new B () ;
a1.print();
You will be able to see,
- Orange colour parts are overriding points.
- Red colour part is Inheritance
- Pink colour highighted part is Casting (Used technic (Up casting))
- Blue colour part is the calling of sub class method.
In the upcasting object (Highlighted Pink), you can see that,
- A -- Super class reference
- The owner is B because, the object is made by B's reference.
- Casting a method of a super class in a subclass or after overriding is called polymorphism. (The process of creating a subclass method by using a superclass reference by using inheritance, casting, overriding is called polymorphism.)
Refer to these Java objects,
- Animal a1 = new Animal ()
- Animal a2 = new Dog ();
- Animal a3 = new BabyDog ();
If you referred to this carefully, you will be able to see that,
- Red colour words are the super class references
- 1st object is a super class object
- 2nd, 3rd are sub class objects
- Because of the animal Dog super class, the object can be created by casting even the baby dog suitable place.


Comments
Post a Comment