example of polymorphism in java

14,363

Solution 1

Looks like homework to me, but I'm bored and Java makes me nostalgic.

List<A> list = new ArrayList<A>();
list.add(new A());
list.add(new A());
list.add(new B());

public void printAll() {
    for(A i : list) {
        System.out.println(i.print());
    }
}

class A {
    public String print() {
        return "A";
    }
}

class B extends A {
    @Override
    public String print() {
        return"B";
    }
}

The output would look like:

    A
    A
    B

The polymorphic part is when different code is executed for the same method call. The loop does the same thing everytime, but different instance methods may actually be getting called.

Solution 2

Have a look at the JDK itself. You'll see polymorphism in lots of places, for example if you look at the java.util Collections. There's a java.util.List interface reference type can behave like an ArrayList or a LinkedList, depending on the runtime type you assign to it.

Solution 3

There are several tutorials as already stated. Here's a quick example I hope is accurate (it's like answering a test)

Parametric polymorphism The same class defines more than one function with the same name but a different array of parameters. The parameter numbers and/or type make it possible to route the call to the right function.

class PolyTest1 {
  private void method1(int a) {}
  private void method1(String b) {}
}

Inheritance polymorphism A class can redefine one of its parent class' methods. The object type makes it possible to call the right function.

public class PolyTest2 extends PolyTest1{

  private void method1(String b) {}
}

Solution 4

The example given in 1st answer of this question makes concept clear. Have a look! Polymorphism vs Overriding vs Overloading

Share:
14,363
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm beginner in Java, so, i'm sorry if the question will be too simple for you.

    Could somebody explain me what the polymorphism is in Java? I need just piece of code that describes it simply.

    Thank you.