Java Polymorphism in OOP's With Example
Java Polymorphism in OOP's With Example
The operation of saving and withdraw is same for Saving and Checking accounts. So
the inherited methods from Account class will work.
For a background, overdraft is a facility where you can withdraw an amount more than
available the balance in your account.
So, withdraw method for privileged needs to implemented afresh. But you do not
change the tested piece of code in Savings and Checking account. This is advantage of
OOPS
Step 1) Such that when the "withdrawn" method for saving account is called a method
from parent account class is executed.
Step 2) But when the "Withdraw" method for the privileged account (overdraft
facility) is called withdraw method defined in the privileged class is executed. This
is Polymorphism.
Method Overriding
Method Overriding is redefining a super class method in a sub class.
The method signature i.e. method name, parameter list and return type have to
match exactly.
The overridden method can widen the accessibility but not narrow it, i.e. if it is
private in the base class, the child class can make it public but not vice versa.
Example
class Doctor{
public void treatPatient(){
// treatPatient method
}
class Surgeon extends Doctor{
public void treatPatient(){
// treatPatient method
}
}
Class run{
public static void main (String args[]){
Doctor doctorObj = new Doctor()
// treatPatient method in class Doctor will be executed
doctorObj.treatPatient();
class X{
public int sum(){
// some code
Ex:
}
}
void sum (int a , int b);
void sum (int a , int b, int c);
class Y extends X{
void sum (float a, double b);
public int sum(){
//overridden method
//signature is same
}
}
obj.treatPatient();
Here the reference variable "obj" is of the parent class, but the object it is pointing to is
of the child class (as shown in the diagram).
If a base class reference is used to call a method, the method to be invoked is decided
by the JVM, depending on the object the reference is pointing to
For example, even though obj is a reference to Doctor, it calls the method of Surgeon,
as it points to a Surgeon object
This is decided during run-time and hence termed dynamic or run-time polymorphism
Polymorphism can be achieved in two of the following ways:
Method Overloading(Compile time Polymorphism)
Method Overriding(Run time Polymorphism)
Method Overloading
To call an overloaded method in Java, it is must use the type and/or the number of arguments to
determine which version of the overloaded method actually to call.
The overloaded methods may have varied return types and the return type single-handedly is
insufficient to make out two versions of a method.
As and when Java compiler encounters a call to an overloaded method, it simply executes the
version of the method whose parameters match the arguments used in the call.
It permits the user to obtain compile time polymorphism with name method name.
An overloaded method can throw different kinds of exceptions.
A method which is overloaded can contain different access modifiers.
}
void mul(int a, int b, int c) {
class Polymorphism {
m.mul(6, 10);
m.mul(10, 6, 5);
Method Overriding
c1.work();
Super Keyword
What if the treatPatient method in the Surgeon class wants to execute the functionality
defined in Doctor class and then perform its own specific functionality?
In this case, keyword supercan be used to access methods of the parent class from the
child class.
The keyword super can be used to access any data member or methods of the super
class in the sub class.
Example:-To learn Inheritance, Polymorphism & super keyword
}
class X{
private int a;
int b;
public void m1(){
System.out.println("This is method m1 of class X");
}
}
class Y extends X{
int c; // new instance variable of class Y
public void m1(){
// overriden method
System.out.println("This is method m1 of class Y");
}
public void m2(){
super.m1();
System.out.println("This is method m2 of class Y");
}
}
Step 2) Save, Compile & Run the code. Observe the output.
Step 3) Uncomments lines # 6-9. Save, Compile & Run the code. Observe the output.
Step 5) Error = ? This is because sub-class cannot access private members of the super
class.
1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating fruits");}
6. }
7. class BabyDog extends Dog{
8. void eat(){System.out.println("drinking milk");}
9. public static void main(String args[]){
10. Animal a1,a2,a3;
11. a1=new Animal();
12. a2=new Dog();
13. a3=new BabyDog();
14. a1.eat();
15. a2.eat();
16. a3.eat();
17. }
18. }
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class MyMainClass {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Example
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
}
Example
In this example we have two classes ABC and XYZ. ABC is a parent class and XYZ is a
child class. The child class is overriding the method myMethod() of parent class. In this
example we have child class object assigned to the parent class reference so in order to
determine which method would be called, the type of the object would be determined at
run-time. It is the type of object that determines which version of the method would be
called (not the type of reference).
To understand the concept of overriding, you should have the basic knowledge
of inheritance in Java.
class ABC{
public void myMethod(){
System.out.println("Overridden Method");
}
}
public class XYZ extends ABC{