user12299845
user12299845

Reputation:

Datatype from subclass or superclass while calling the subclass constructor?

I'm a novice with java and I tried to make a simple polymorphism program.

public abstract class Animal {
    public abstract void action();
}

public class Cow extends Animal {

    @Override
    public void action() {
        System.out.println("Im a cow.");
    }
}
public class Sheep extends Animal {

    @Override
    public void action() {
        System.out.println("Im a sheep.");
    }
}
1 import java.util.ArrayList;
2
3 public class Main {
4
5   public static void main(String[] args) {
6       ArrayList<Animal> animals = new ArrayList<Animal>();
7       Animal cow = new Cow();
8       Animal sheep = new Sheep();
9       animals.add(cow);
10      animals.add(sheep);
11
12      for (Animal animal : animals) {
13          animal.action();
14      }
15  }
16 }

I was wondering if there is a difference between this and changing the datatype from line 7 to Cow -> Cow cow = new Cow(); and the datatype from line 8 to Sheep -> Sheep sheep = new Sheep(); I'm very curious because the output is exactly the same.

Upvotes: 0

Views: 178

Answers (1)

Jack
Jack

Reputation: 133619

There is no difference, cow variable is used just to add it to a ArrayList<Animal>.

There could be a difference according to a specific usage case since a Cow variable could have additional methods which are not present in Animal but semantically they'll be behave equivalently.

The only difference is what you are allowed to invoke on the cow variable.

In general it's always better to use the least specific type you can so that you are sure you are not using any specific feature that you wouldn't want to use. This same principle applies to animals variables, a better declaration would be:

List<Animal> animals = new ArrayList<>();

Upvotes: 1

Related Questions