Inheritance Representation Exercises

  < Previous  Next >
  1. Given the following classes, which is a better representation of inheritance: the UML Diagram or the circle within a circle? Why?

    public class Mammal{
        protected double age; // in years
    
        public Mammal(){
            System.out.println( "Mammal()" );
        }
    
        public Mammal( double age ){
            this.age = age;
            System.out.println( "Mammal("+age+")" );
        }
    
        public double getAge(){
            return age;
        }
    
        public void setAge( double age ){
            this.age = age;
        }
    
        public void speak(){
            System.out.println("Mammal is speaking");
        }
    }
    

    and

    public class Dog extends Mammal{
        protected String breed;
    
        public Dog(){
            System.out.println( "Dog()" );
        }
    
        public Dog( double age, String breed){
            this.age = age;
            this.breed = breed;
            System.out.println( "Dog("+age+", "+breed+")" );
        }
    
        public String getBreed(){
            return breed;
        }
    
        public void setBreed( String breed ){
            this.breed = breed;
        }
    
        @Override
        public void speak(){
            System.out.println("Woof, woof");
        }
    }
    

    UML Diagram of a Mammal and Dog class (Dog has an open arrow to Mammal)Diagram of a Mammal class within a Dog class