Solutions to the Practice Questions#

Hierarchies for Inheritance#

  1. The following code goes in the Rectangle class:

    public double calcDiagonalLength(){
       return Math.sqrt(width * width + length * length);
    }//calcDiagonalLength
    
  2. In main method:

    Square aSquare = new Square(8);
    System.out.println("Length of diagonal: " +  aSquare.calcDiagonalLength());
    
  3. In main method:

    Rectangle aRect = new Rectangle(5, 3);
    System.out.println("Length of diagonal: " + aRect.calcDiagonalLength());
    

Back to Questions

Setters and Getters#

  1. In Rectangle class:

    public void setWidth(double width){
       this.width = width;
    }
    
  2. In Square class:

    public void setWidth(double width){
       this.width = width;
       this.length = width;
    }
    

Back to Questions

Default Constructor#

  1. In class Rectangle:

    public Rectangle(){
       this(1, 2);
    }
    
  2. In class RightTriangle:

    public RightTriangle(){
       this(2, 5);
    }
    
  3. In class Circle:

    public Circle(){
       this(1);
    }
    

A Representation to Print#

  1. In class Circle:

    @Override
    public String toString(){
       return getClass().getName() + " radius = " + radius;
    }
    
  2. In class RightTriangle:

    @Override
    public String toString(){
       return getClass().getName() + " base = " + base + 
              " height = " + height;
    }
    
  3. No code to write as toString() will be correctly inherited from the Rectangle class.

Back to Questions

Every Class Extends Object#

stringBuilder Hierarchy
arrayList Hierarchy
Four Hierarchies
[Back to Questions](chapter3:extendsObject:practice)