Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of it in OOP occurs when a parent class reference is used to refer to a child class object.
It is one of the OOPs features that allow us to perform a single action in different ways.
Example 1.
public class Animal{
…
public void sound()
{
System.out.println(“Animal is making a sound”);
}
}
Example 2.
public class Horse extends Animal{
…
@Override public void sound(){
System.out.println(“Neigh”);
}
}
And
public class Cat extends Animal{
…
@Override public void sound(){
System.out.println(“Meow”);
}
}
Types of Polymorphism are:
- Compile-time polymorphism
- Runtime polymorphism
1) Static Polymorphism is known at compile-time.
2) Dynamic Polymorphism also is known at runtime.
Compile type
A polymorphism that is resolved during compile time is known as static polymorphism. Method overloading is an example of compile-time polymorphism.
Method Overloading: This allows us to have more than one method having the same name if the parameters of methods are different in number, sequence and data types of parameters.
Runtime Polymorphism
It is also known as Dynamic Method Dispatch. Dynamic is a process in which a call to an overridden method is resolved at runtime, that’s why it is called runtime polymorphism.
Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details, for example, sending SMS, you just type the text and send the message. You don’t know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
Abstraction Properties
- A class which contains the abstract keyword in its declaration is known as abstract class.
- Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); )
- But, if a class has at least one abstract method, then the class must be declared abstract.
- If a class is declared abstract, it cannot be instantiated.
- To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
- If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
Example:-
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println(“running safely..”);}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
You may also like inheritance
Leave a Reply