Generic Classes Exercises

  < Previous  Next >
  1. Given the following class definitions:
    public class Pet{ /*...*/ }
    public class Dog extends Pet{ /*...*/ }
    public class Cat extends Pet{ /*...*/ }
    Will the following code compile? If not, why?
    public class PetInventory< T extends Pet >{
        /*...*/
    
        public static void main( String[] args ){
            PetInventory< Dog > dogs = new PetInventory< Dog >();
            PetInventory< Pet > pets = dogs;
        }
    }
  2. Write a generic Calculator class with two private fields to store two numbers and complete at least the methods below. Allow each of the numbers to be a different data type.
    Calculator< Integer, Double > calc = new Calculator< Integer, Double >( 2, 3.141596 );
    System.out.println( calc.add() );
    System.out.println( calc.multiply() );
    
    Calculator< Double, Integer > calc2 = new Calculator< Double, Integer >( 2.71828, 7 );
    System.out.println( calc2.add() );
    System.out.println( calc2.multiply() );
    Hint: Consider using the Number class, which is the parent class of Double, Integer, etc. Then, consider performing all math operations on double values (see the doubleValue() method).