Example polymorphism in java

I am starting in Java, so sorry if the question is too simple for you.

Can someone explain to me what polymorphism is in Java? I only need a piece of code that just describes it.

Thank.

+3
source share
4 answers

I like homework, 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 result will look like this:

    A
    A
    B

The polymorphic part is when different code is executed for the same method call. The loop does the same thing every time, but actually you can call different instance methods.

+3
source

JDK. , , java.util Collections. java.util.List ArrayList LinkedList, , .

+2

, . , , ( )

, . / .

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

. .

public class PolyTest2 extends PolyTest1{

  private void method1(String b) {}
}
+2

The example given in the 1st answer to this question makes the concept understandable. Take a look! Polymorphism vs Overload and Overload

+1
source

All Articles