examples of polymorphism in java

0

What is Polymorphism?

Answer: Polymorphism means many forms.

A single object can refer to the super-class or sub-class depending on the reference type which is called polymorphism.

Example:

Public class Manipulation(){ //Super class
public void add(){
}
}
public class Addition extends Manipulation(){ // Sub class
public void add(){
}
public static void main(String args[]){
Manipulation addition = new Addition();//Manipulation is reference type and Addition is reference type
addition.add();
}
}

All Contributions

Polymorphism example using java programming OOP

/******************************************************************************

Polymorphism example using java programming OOP
*******************************************************************************/
public abstract class Shape
{
    public abstract void drawShape();
}

public class Triangle extends Shape
{
    public void drawShape()
    {
        System.out.println("\n    *\n   * *\n  * * *\n * * * *\n* * * * *\n");
    }
}

public class Square extends Shape
{
    public void drawShape()
    {
        System.out.println("\n* * * *\n* * * *\n* * * *\n");
    }
}

public class Rectangle extends Shape
{
    public void drawShape()
    {
        System.out.println("\n* * * * * *\n* * * * * *\n* * * * * *\n");
    }
}
public class Rabea extends Shape
{
    public void drawShape()
    {
        System.out.println("\n  * * *\n* * * * *\n  * * *\n");
    }
}
public class Main
{
	public static void main(String[] args) {
		Shape T=new Triangle();
		Shape S=new Square();
		Shape R=new Rectangle();
		Shape n=new Rabea();
		
		T.drawShape();
		S.drawShape();
		R.drawShape();
		n.drawShape();
	}
}

example of Polymorphism in java

class Main{
//class PolymorphismDemo {
  public static void main(String[] args) {
    m(new GraduateStudent());
    m(new Student());
    m(new Person());
    m(new Object());
  }

  public static void m(Object x) {
    System.out.println(x.toString());
  }
}

class GraduateStudent extends Student {
}

class Student extends Person {
  public String toString() {
    return "Student";
  }
}

class Person extends Object {
  public String toString() {
    return "Person";
  }
}

total contributions (2)

New to examplegeek.com?

Join us