Inheritance

From Java Programming II
Jump to: navigation, search

Classes and Objects in Java

Learning Outcomes

Reference: Java How to Program

  • How inheritance promotes software reusability.
  • The notions of superclasses and subclasses and the relationship between them.
  • To use keyword extends to create a class that inherits attributes and behaviors from another class.
  • To use access modifier protected to give subclass methods access to superclass members.
  • To access superclass members with super.
  • How constructors are used in inheritance hierarchies.
  • The methods of class Object, the direct or indirect superclass of all classes.

Video Lecture

Lecture Notes


Quiz 02 Fall 2015

Lecture notes

  • Inheritance: a class (subclass) inherits all attributes and methods of another class (superclass).
  • Inheritance is an object oriented programming concept that allow us to program from generic classes to more specific classes.
  • In Java, we used the keyword extends to perform inheritance.
  • Any class in Java implicitly inherits from the Object class.
  • There are two types of inheritance:
    • Direct inheritance: when a subclass inherits directly from its superclass
    • Indirect inheritance: when a sub class inherits from a superclass through another intermediate superclass.
  • Multiple inheritance is not allowed in Java. Only single inheritance is allowed. in C++ multiple inheritance is supported.
  • Inheritance is also known as is-a relationship. In an is-a relationship,an object of a subclass also can be treated as an object of its superclass.
  • Composition is known as has-a relationship. In a has-a relationship, a class object con- tains references to objects of other classes.
  • Generic are usually the superclasses
  • Specific are subclasses that implement specific behavior
  • Why inheritance is useful?
    • to reduce the size of the code and development time
    • make the code modification easier and more efficient
    • improve modularity and promote software reuse
  • When a subclass inherits methods of a superclass, it can either:
    • maintain the same definition
    • or override the method to adapt it to the specificity of the subclass. Example the earning() method.
  • The constructor of the subclass must first call the constructor of the superclass using the keyword super to initialise the common attributes of both classes.
  • The private attribute of the superclass cannot be directly accessed in the subclass. It is possible to use protected access specifier to allow for such an access from the subclass or inside the same package.
  • A superclass’s protected members have an intermediate level of protection between public and private access. They can be accessed by members of the superclass, by members of its subclasses and by members of other classes in the same package.

Programs' Code

Without Using Inheritance

In what follows, we have two classes of CommissionEmployee, and BasePlusComissionEmployee. The only difference is that the BasePlusComissionEmployee has a base salary in addition to attributes of ComissionEmployee, and thus its earning method is slightly different.

The code below shows the implementation of both classes without using inheritance. Observe the following

  • There is a lot of redundancy in both codes
  • BasePlusComissionEmployee has more than 110 lines of code.

Certainly, this programming style is not efficient. It is also not easy to modify the code of the related classes.
Solution: using inheritance as shown in the next section

/**************************************************************************
* (C) Copyright 1992-2003 by Deitel & Associates, Inc. and *
* Prentice Hall. All Rights Reserved.                                    *
**************************************************************************/
 

CommissionEmployee class

package withoutinheritance;

/**
*
* @author akoubaa
*/
public class CommissionEmployee {
   private String firstName;
   private String lastName;
   private String Ssn;
   private double grossSales;
   private double commissionRate;
   
   public CommissionEmployee(String first, String last, String ssn, double sales, double rate ){
       firstName = first;
       lastName = last;
       Ssn = ssn;
       setGrossSales(sales); //we have to perform data validation
       setCommissionRate(rate);//we have to perform data validation
   }
   
   public String getFirstName(){
       return firstName;
   }
   
   public void setFirstName(String firstName){
       this.firstName = firstName;
   }
   
   public String getLastName(){
       return lastName;
   }
   
   public void setLastName(String last){
       lastName=last;
   }
   
   public String getSsn(){
       return Ssn;
   }
   
   public void setSsn (String ssn){
       Ssn=ssn;
   }
   
   public double getGrossSales(){
       return grossSales;
   }
   
   public void setGrossSales(double sales){
       if (sales>=0.0)//data validation
           grossSales = sales;
       else
           throw new IllegalArgumentException("Gross sales must be greater than 0.0");
   }
   
   public double getCommissionRate(){
       return commissionRate;
   }
   
   public void setCommissionRate(double rate){
       if ((rate>=0.0)&&(rate<1.0))
           commissionRate = rate;
       else
           throw new IllegalArgumentException("Commission rate must in >=0.0 and <1.0");
   }
   
   public double earning(){
       return commissionRate*grossSales;
   }
   
   @Override
   public String toString(){
       return String.format("commission employee: %s %s\n"
               + "social security number: %s \n"
               + "gross sales: %.2f \n"
               + "commission rate: %.2f", firstName, lastName, Ssn, 
               grossSales, commissionRate);
   }
   
}

BasePlusCommissionEmployee Class

 package withoutinheritance;
public class BasePlusCommissionEmployee {
   private String firstName;
   private String lastName;
   private String Ssn;
   private double grossSales;
   private double commissionRate;
   
   private double baseSalary; //base salary per week
   
   public BasePlusCommissionEmployee(String first, String last, 
           String ssn, double sales, double rate, 
           double salary){
       firstName = first;
       lastName = last;
       Ssn = ssn;
       setGrossSales(sales); //we have to perform data validation
       setCommissionRate(rate);//we have to perform data validation
       setBaseSalary(salary);
   }
   
   public void setBaseSalary(double baseSalary){
       if (baseSalary>0.0)
           this.baseSalary=baseSalary;
       else
           this.baseSalary=0.0;
   }
   
   public double getBaseSalary(){
       return baseSalary;
   }
   
   public String getFirstName(){
       return firstName;
   }
   
   public void setFirstName(String firstName){
       this.firstName = firstName;
   }
   
   public String getLastName(){
       return lastName;
   }
   
   public void setLastName(String last){
       lastName=last;
   }
   
   public String getSsn(){
       return Ssn;
   }
   
   public void setSsn (String ssn){
       Ssn=ssn;
   }
   
   public double getGrossSales(){
       return grossSales;
   }
   
   public void setGrossSales(double sales){
       if (sales>=0.0)
           grossSales = sales;
       else
           throw new IllegalArgumentException("Gross sales must be greater than 0.0");
   }
   
   public double getCommissionRate(){
       return commissionRate;
   }
   
   public void setCommissionRate(double rate){
       if ((rate>=0.0)||(rate<1.0))
           commissionRate = rate;
       else
           throw new IllegalArgumentException("Commission rate must in >=0.0 and <1.0");
   }
   
   public double earning(){
       return baseSalary+(commissionRate*grossSales);
   }
   
   @Override
   public String toString(){
       return String.format("base plus commission employee: %s %s\n"
               + "social security number: %s \n"
               + "gross sales: %.2f \n"
               + "commission rate: %.2f\n" 
               + "base salary: %.2f",
               firstName, lastName, Ssn, 
               grossSales, commissionRate, baseSalary);
   }
   
}

Using Inheritance

Considering the drawbacks of the first approach, we now use an important concept in Object Oriented Programming that is inheritance. Observe the following:

  • The class CommissionEmployee, that is the generic class (or superclass) remains unchanged (same code as above)
  • The class BasePlusComissionEmployee now extends the class CommissionEmployee
  • How much code is reduced with using inheritance: 50 lines with inheritance as compared to more than 110 lines without using inheritance in the BasePlusComissionEmployee.


package usinginheritance;

/**
*
* @author akoubaa
*/
public class BasePlusCommissionEmployee extends CommissionEmployee{
   
   private double baseSalary; //base salary per week 
   
   public BasePlusCommissionEmployee (String first, String last, 
           String ssn, double sales, double rate, 
           double salary){
       super(first, last, ssn, sales, rate);
       setBaseSalary(salary);
   }
   
   
   public void setBaseSalary(double salary){
       if (salary>=0)
           baseSalary = salary;
   }
   
   public double getBaseSalary(){
       return baseSalary;
   }
   
   @Override
   public double earning(){
       return baseSalary+(super.earning());
   }
   
   @Override
   public String toString(){
       return String.format("base plus %s\n" 
               + "base salary: %.2f",
               super.toString(), baseSalary);
   }
   
}