OOP IN JAVA : (POLYMORPHISM)
Polymorphism
Polymorphism is one of the core concepts in OOP languages and describes the concept wherein you can use different classes with the same interface. Each of these classes can provide its own implementation of the interface.
After overriding a method of a super class in a sub class, casting it and making the sub class method run through the super class reference. Using overriding inheritance casting concept 3 to call the sub class from the super class reference.
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object, for the Example :-
class Person {
public void teach(){
System.out.println("Person can teach");
}
}
class Teacher extends Person {
public void teach() {
System.out.println ("Teacher can teach in a school");
}
}
public class TestTeacher {
public static void main(String args[]) {
Person person = new Person(); //Person reference and object
Person another_ person = new Teacher(); //Person reference, Teacher object
Teacher teacher = new Teacher(); //Teacher reference and obj. person. teach();//output: Person can teach // Here you can see Teacher object's method is executed even-
// -though the Person reference was used
another_ person. teach();//output: Teacher can teach in a school teacher. teach();//output: Teacher can teach in a school
}
}
THANKYOU!
Comments
Post a Comment