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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With