up previous next contents
Next: What protected really means Up: Extending Classes Previous: An extended class   Contents

A simple example

  • A simple example of extending a base Animal class:
    public abstract class Animal
    {
      protected boolean hasColdNose;
    
      public abstract String speak();
    
      public void setHasWetNose(boolean hasColdNose) {
        this.hasColdNose = hasColdNose;
      }
      public boolean hasColdNose() {
        return hasColdNose;
      }
    }
    
    public class Dog extends Animal
    {
      public Dog() {
        hasColdNose = true;
      }
      public String speak() {
        return "woof";
      }
    }
    
    public class Bird extends Animal
    {
      public Bird() {
        hasColdNose = false;
      }
      public String speak() {
        return "chirp";
      }
    }
    

    public class Main
    {
      public Main() {
        Animal fido = new Dog();
        Animal bigbird = new Bird();
        System.out.println( "fido says " + fido.speak() );
        System.out.println( "bigbird says " + bigbird.speak() );
      }
    
      public static void main(String[] args) {
        new Main();
      }
    }
    


up previous next contents
Next: What protected really means Up: Extending Classes Previous: An extended class   Contents