11. Inheritance 1

Animal. Dog. Cat. Borzoi. Boxer. Abstract example: A, B, C.

Relatively simple

Create the following classes.

  • Animal is an abstract class

    • Animal(String kind) constructor to create an animal of a certain kind.
    • public String noise(): an abstract method
    • public void speak(): print out “a [kind] says [noise()].”
  • Cat is a subclass of Animal. It makes the “miaou” noise.

  • Dog is a subclass of Animal. It makes the “ruff” noise. Dogs can also do public void trick(), which prints out “shake”.

  • Borzoi is a subclass of Dog. The Borzoi does not bark, the only noise it makes is a “whine”.

  • Boxer is a subclass of Dog. The Boxer knows the “tug of war” trick.

Discuss how they can and cannot be used in a Java program. See the testAnimals function (also as plain text).

Complexified

This example is more abstract but reviews the same ideas.

    public class A {
        public void p() { print("hi"); q(); }
        public void q() { print("Sally"); }
    }
    public class B extends A {
        public void p() { super.p(); print("bye"); }
    }
    public class C extends A {
        public void q() { print("Ava"); }
        public void r() { print("$1000"); }
    }

Questions about the code or as text.

Assignment: Open the “questions about the code” document and answer the questions without actually running the code. If a line does not compile, explain why. If it does compile, explain what it does when it runs.

Last modified February 27, 2024: Clarified second part. (bfb8ba4)