Home Java Introduction Decisions Loops Classes Access Inheritance Inner Classes Arrays Exceptions Strings Generics Container Input/Output MultiThreading jdk8 Versions Books

Inheritance


Contents



Inheritance is about using the base classes to bring in functionality to the derived class.Composition is the ability for a class to contain objects of another class.

Composition



File: Composition.java

class Item
{
  String name ;
  float price ;
  Item( String nameP , float priceP )
    {
        name=nameP  ;
        price=priceP ;
    }
}

class Customer
{
    String name ;
    int tableNo ;
    Customer( String nameP , int tableNoP )
    {
        name=nameP  ;
        tableNo=tableNoP ;
    }

}

class Order
{
  Item item1 ;
  Item item2 ;
  Customer customerObject ;
  Order(Item item1P, Item item2P ,
    Customer customerP )
   {
      item1 = item1P  ;
      item2 = item2P  ;
      customerObject = customerP ;
   }
  public String toString()
   {
     String result =  "First Item: " + item1.name  ;
     result +=  "\nSecond Item: " + item2.name  ;
     result +=  "\nFor Customer: " + customerObject.name  ;
     result +=  "\nFor Table No: " + customerObject.tableNo  ;
     return result ;
   }

}

public class Composition
{
   public static void main( String args[] )
   {
       Item item1 = new Item( "Burger" , 1.50f ) ;
       Item item2 = new Item( "Fries" , 1.00f ) ;
       Customer customer1 = new Customer( "Buster Douglas" ,
                            4 ) ;
       Order orderObj = new Order(item1, item2, customer1  ) ;
       System.out.println( orderObj )  ;



   } //public static void main( String args[] )


}
First Item: Burger
Second Item: Fries
For Customer: Buster Douglas
For Table No: 4

Inheritance



File: Inheritance1.java

class Person
{
  String name ;
  int age ;
  Person()
   {
       System.out.println( "Person()" ) ;
   }

}

class Employee extends Person
{
  String jobTitle ;
  String DeptName ;
  String ssn ;
  Employee()
   {
       System.out.println( "Employee()" ) ;
   }
}


class Person1
{
  String name ;
  int age ;
  Person1()
   {
       System.out.println( "Person1()" ) ;
   }
  Person1( String nameP , int ageP )
   {
       name = nameP ;
       age = ageP ;
       System.out.println( "Person1() with arguments" ) ;
   }

   void print()
    {
        System.out.println("name: " + name +
            " age: " + age ) ;
    }

}

class Employee1 extends Person1
{
  String jobTitle ;
  String DeptName ;
  String ssn ;
  Employee1( String nameP, int ageP,
    String jobTitleP, String DeptNameP, String ssnP )
   {

       //super()
       //If we don't supply super then the default super
       // ( without any args constructor ) if
        // it exists will be called for us
       //jobTitleP, DeptNameP, ssnP

       super( nameP , ageP ) ;
       jobTitle = jobTitleP ;
       DeptName = DeptNameP ;
       ssn = ssnP ;
       System.out.println( "Employee1 with arguments()" ) ;

   }

   void print()
    {
        //Calling a base class method from derived class
        //if it has the same method name
         super.print() ;
         System.out.println("Job Title: " + jobTitle +
                    " Dept: " + DeptName + " ssn:" + ssn ) ;

    }
}



public class Inheritance1
{
   public static void main( String args[] )
   {
     Employee employeeObject = new Employee() ;
     System.out.println( "--------" ) ;
     Employee1 employeeObject1 = new Employee1("Joe Bugner", 35 ,
       "Programmer", "Engineering" , "119701024" ) ;
     employeeObject1.print() ;

   } //public static void main( String args[] )


}
Person()
Employee()
--------
Person1() with arguments
Employee1 with arguments()
name: Joe Bugner age: 35
Job Title: Programmer Dept: Engineering ssn:119701024
The above program shows how we can use inheritance and deal with constructors. Also how we can call base class functions and constructors from derived class.

Upcasting



File: Upcasting.java

class Person
{
  String name ;
  int age ;
  Person()
   {
       System.out.println( "Person()" ) ;
   }
  Person( String nameP , int ageP )
   {
       name = nameP ;
       age = ageP ;
       System.out.println( "Person() with arguments" ) ;
   }

   void print()
    {
        System.out.println("name: " + name +
            " age: " + age ) ;
    }

}

class Employee extends Person
{
  String jobTitle ;
  String DeptName ;
  String ssn ;
  Employee( String nameP, int ageP,
    String jobTitleP, String DeptNameP, String ssnP )
   {

       //super()
       //If we don't supply super then the default super
       // ( without any args constructor ) if
        // it exists will be called for us
       //jobTitleP, DeptNameP, ssnP

       super( nameP , ageP ) ;
       jobTitle = jobTitleP ;
       DeptName = DeptNameP ;
       ssn = ssnP ;
       System.out.println( "Employee with arguments()" ) ;

   }

   //Good idea. Compile time checking .
   //if base class does not have this method we
   //get an error
   @Override
   void print()
    {
        //Calling a base class method from derived class
        //if it has the same method name
         super.print() ;
         System.out.println("Job Title: " + jobTitle +
                    " Dept: " + DeptName + " ssn:" + ssn ) ;

    }
}



public class Upcasting
{
   public static void main( String args[] )
   {

     Employee employeeObject1 = new Employee("Joe Bugner", 35 ,
       "Programmer", "Engineering" , "119701024" ) ;
     employeeObject1.print() ;

     //Allowed since an employee is a Person conceptually
     Person personObject = employeeObject1  ;
     //ok to call base class functions
     personObject.print() ;

     //Downcasting is not allowed
     // A person may be a student not an employee
     //employeeObject1 = personObject ;

     //Allowed. If it fails while running we get a run time error
     employeeObject1 = (Employee)personObject ;


   } //public static void main( String args[] )


}
C:\WebSite\Learn\2\Java\inheritance>java Upcasting
Person() with arguments
Employee with arguments()
name: Joe Bugner age: 35
Job Title: Programmer Dept: Engineering ssn:119701024
name: Joe Bugner age: 35
Job Title: Programmer Dept: Engineering ssn:119701024
The above example shows how we can upcast, downcast and use the "@Override" annotation.

Final



File: Final.java

class Person
{
  String name ;
  int age ;
  int id ;
  private final int id1 = 1 ;
  private final int id2  ;

  void method()
   {

   }

  Person()
   {
       id2 = 2 ;
       System.out.println( "Person()" ) ;
   }
  Person( String nameP , int ageP )
   {
       //Every constructor must initialize
       id2 = 2 ;
       name = nameP ;
       age = ageP ;
       System.out.println( "Person() with arguments" ) ;
       methodArgFinal( 4 ) ;
   }

   //An argument can be final
   void methodArgFinal( final int x1 )
    {
      //can't change x1 ;
      // x1 = 5 ;
    }

   public final void methodFinal(  )
    {
      //can't change x1 ;
      // x1 = 5 ;
    }

   //Does not work with private final methods
   //private is private to class cannot be accessed
   //from outside
   private final void methodFinal1(  )
    {
      //can't change x1 ;
      // x1 = 5 ;
    }


   void print()
    {
        System.out.println("name: " + name +
            " age: " + age ) ;
    }

}

class Employee extends Person
{
  String jobTitle ;
  String DeptName ;
  String ssn ;
  Employee( String nameP, int ageP,
    String jobTitleP, String DeptNameP, String ssnP )
   {

       //super()
       //If we don't supply super then the default super
       // ( without any args constructor ) if
        // it exists will be called for us
       //jobTitleP, DeptNameP, ssnP

       super( nameP , ageP ) ;
       jobTitle = jobTitleP ;
       DeptName = DeptNameP ;
       ssn = ssnP ;
       System.out.println( "Employee with arguments()" ) ;

   }

   //Can't override a final method
   //error: methodFinal() in Employee cannot override methodFinal() in Person
   /*
   public final void methodFinal(  )
    {
      //can't change x1 ;
      // x1 = 5 ;
    }
    */


   //Use @Override to get compiler error
   //@Override
   public final void methodFinal1(  )
    {
    }

   //Good idea. Compile time checking .
   //if base class does not have this method we
   //get an error
   @Override
   void print()
    {
        //Calling a base class method from derived class
        //if it has the same method name
         super.print() ;
         System.out.println("Job Title: " + jobTitle +
                    " Dept: " + DeptName + " ssn:" + ssn ) ;

    }
}

//This class cannot have any derived classes
final class A
{
}

/*
//Final.java:120: error: cannot inherit from final A
class B extends A
{
}
*/



public class Final
{
   public static void main( String args[] )
   {

     final Employee employeeObject1 = new Employee("Joe Bugner", 35 ,
       "Programmer", "Engineering" , "119701024" ) ;
      //We cannot change the reference value that
     //employeeObject1 is holding.
     // error: cannot assign a value to final variable employeeObject1
     //  employeeObject1 = new Employee("Alan Turing", 35 ,
     //  "Programmer", "Engineering" , "119701024" ) ;
     //We can, however, change the values of it's data members
     employeeObject1.age = 36 ;


   } //public static void main( String args[] )


}

Exercises:
1) Add a "toString()" method to the "Item" class in "Composition.java" code so that the "Order" class does not access the "name" property directly.

File: ex1.java














1)
File: soln1.java
2)