Java Tutorial Series - OOPS - Polymorphism

Let's see how polymorphism is implemented and how it works in this article. We will also look at upcasting and down casting in Java.

Polymorphism in Java -

Polymorphism means achieving a single task in multiple ways, or in many forms.

We have broadly 2 categories of Polymorphism
  1. Compile time/ early binding/ static binding/ overloading
  2. Run time/ late binding/ dynamic binding/ overriding

//Parent class
pubic class Plant {
public void grow() {
System.out.println("Plant growing");
}
}

public class Tree extends Plant {
public void grow() {
System.out.println("Tree growing");
}
}

public static void main(String[] Args) {
Plant plant = new Tree(); // this is polymorphism
plant.grow();
}

//Output -
Tree growing

object of child class is pointing to reference variable of parent class. In simple words, remember this -

Parent pc = new child();

Upcasting and down casting in Java - 

Let's have a look at how upcasting and down casting works in Java by having a look at below example -

class Machine {
public void Start() {
System.out.println("Machine Started");
}

}


class Camera extends Machine {
public void Start() {
System.out.println("Car Started");
}

public void Snap() {
System.out.println("Photo Taken");
}

}

public class App {
public static void main(String[] Args) {
Machine machine1 = new Machine();
Camera camera1 = new Camera();

machine1.Start()  ;          // prints Machine Started
camera1.Start()   ;          //prints Camera Started
camera1.Stop()   ;          //prints Photo Taken

//upcasting
Machine machine2 = new Camera() ;   //polymorphism
machine2.Start();                                   // prints Car Started
// error : machine2.Snap();

In above code we tried to call snap method using object of Camera class and with Machine's reference which is not possible but it can be achieved using down casting concept in Java, let's have a look at it.

Down casting in Java -
Machine machine3 = new Camera();
Camera camera2 = (Camera)machine3;                //Downcasting achieved here
camera2.Snap();                                                     //prints "Photo taken"
camera.Start();                                                       //prints "Camera started"


It is not recommended to use Downcasting though.

Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD