0

I am trying to understand this example of Java abstraction I came across. Under what conditions would I want to write:

Animal myPig = new Pig();

instead of:

Pig myPig = new Pig();

Here is the code:

// Abstract class
abstract class Animal {
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep() {
    System.out.println("Zzz");
  }
}

// Subclass (inherit from Animal)
class Pig extends Animal {
    @Override
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
}

class Main {
  public static void main(String[] args) {
    // Animal myPig = new Pig(); // Create a Pig object
    Pig myPig = new Pig(); // Line in question
    myPig.animalSound();
    myPig.sleep();
  }
}

Both lines give the same result, I just can't see any advantage of one use of the other or in what scenario one of them would make more sense.

mastercooler6
  • 377
  • 2
  • 16

0 Answers0