Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

example of polymorphism in java [closed]

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.

like image 750
user748394 Avatar asked Feb 24 '23 05:02

user748394


2 Answers

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.

like image 60
Cogsy Avatar answered Feb 26 '23 21:02

Cogsy


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.

like image 34
duffymo Avatar answered Feb 26 '23 21:02

duffymo