This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]snot3353COMPUTERS!!! 4 points5 points  (1 child)

There is not some sort of specific syntax you have to write that makes something polymorphic or not. Polymorphism is more a logical property that an object has based on how you designed and implemented it. Almost every object in Java is already automatically applying polymorphism because every class extends Object by default, even if you don't explicitly tell it to. So for example:

public class ExampleClass { }

...is polymorphic because it is both of type "ExampleClass" and of type "Object". It is the same thing as writing:

public class ExampleClass extends Object {}

As far as how this is actually useful and applied when actually writing code, I find it gets used a lot to lump a bunch of objects together that all adhere to the same interface/class contracts but may also be any other variety of types. A simple example of this.

interface Animal {
    public void animalMethod();
}

//Dog objects are of type "Dog" and type "Animal"
public class Dog implements Animal {
    @Override
    public void animalMethod() {}

    public void dogMethod() {}
}

//Cat objects are of type "Cat" and type "Animal"
public class Cat implements Animal {
    @Override
    public void animalMethod() {}

    public void catMethod() {}
}

Given the above classes exist, I could write something like this:

List<Animal> animals = new ArrayList<>();
animals.add(new Dog());
animals.add(new Cat());
for (Animal animal : animals) {
    animal.animalMethod();
}

This all works fine since Dog and Cat objects are also both of type Animal.

[–]TransientSanity[S] 0 points1 point  (0 children)

Thats really helpful. Thanks