0

I'm relatively new to the topic of polymorphism and inheritance, but I've had a burning question. Consider this code:

public class Food {
    public static void eat() {
        System.out.println("This food is great.");
    }
}

public class Cake extends Food {
    public static void eat() {
        System.out.println("This cake is great.");
    }
}

Of course, you could instantiate a Cake object like this:

Cake c = new Cake();

but I've also been told you could instantiate a Cake object like this:

Food c = new Cake();

My question is: What's the difference between the two? I do not see the point of the second one but I'm sure there has to be a situation where it would be useful?

Daniel
  • 137
  • 2
  • 11
  • Let's say you have a `Fridge`. You put a lot of different `Food` inside it. You could keep track of the food with several lists: `List`, `List`, `List`. `List` and so on. Or you could simply keep track of everything with a `List`. That's why it's useful to have a polymorphic reference. You don't know which `Food` it is, but you know for sure it [***is-a***](https://en.wikipedia.org/wiki/Is-a) `Food`. – BackSlash Dec 28 '17 at 17:58
  • Thanks for your response. I understand what you are going at, but I'm not sure that quite hits what I was asking. I wanted to know the difference between the two instantiations that I included in my question. – Daniel Dec 28 '17 at 18:27
  • Because most of the time, you only need to know *what* something does, not *how* it does it. If I have a list of items, I usually don't care whether it's an array, a linked list, or something in a database. – chrylis -cautiouslyoptimistic- Dec 28 '17 at 18:35
  • There is no difference between the two instantiations. Both create a new Cake (exactly the same), but store it (more precise: its reference) in different variables. The first variable that will only accept Cakes, the second all kinds of Food. So if you later want to store a Potato in c, that will only work with the second variable. – Ralf Kleberhoff Dec 28 '17 at 18:59

0 Answers0