Title: ObjectOriented Programming: Inheritance
1Object-Oriented ProgrammingInheritance
2Introduction
- Besides composition, another form of reuse is
inheritance. - With inheritance, an object can inherit behavior
from another object, thus reusing its code. - The class inheriting is called a subclass (or
derived class). - The class inherited from is called a superclass
(or base class).
3Subclass
- A subclass usually adds to its superclass, thus
creating a more specialized object. - A subclass may be the superclass for its own
subclass, thus creating a class hierarchy. - The immediate superclass for a subclass is called
its direct superclass. - A superclass above the direct superclass is
called an indirect superclass. - In Java, the Object class is a direct or indirect
superclass to all other classes.
4Multiple Inheritance
- Java, unlike C, does not support multiple
inheritance (Java allows only one direct
superclass). - Java uses interfaces to provide some of this
capability. - With an interface, multiple classes can support
some of the same behavior.
5Inheritance
- Many projects deal with closely-related cases.
- Coding for these minor differences in a large
project can obscure the overall effort. - With inheritance, a superclass can define the
general behavior, then each subclass can
specialize this behavior.
6Inheritance Relationships
- Inheritance is known as an is-a relationship.
- Composition is a has-a relationship.
- A car is a vehicle.
- A car has a steering wheel.
7Protected Members
- If a member is given the protected access
modifier, then subclasses of that class may
access it, as well as classes in the same package
8Overriding Methods
- A subclass may override a method of a superclass
by declaring a method with the same signature. - When overriding a method, its access modifier
cannot be changed to be more restrictive (for
example, public to private). - This is so the subclass can respond to the same
messages as the superclass.
9Examples
- The next several examples illustrate inheritance.
- A commissioned employee is created.
- A basecommission employee is created without
inheriting from the commissioned employee class. - A basecommission employee is created by
inheriting from commissioned employee, but cannot
access private fields. - The commissioned employee is changed to have
protected variables so that a basecommission
employee can access them. - The commissioned employee fields are made private
again but given accessors for the subclass
basecommission employee to use.
10// Fig. 9.4 CommissionEmployee.java //
CommissionEmployee class represents a commission
employee. public class CommissionEmployee
extends Object // extends Object not required
here private String firstName private
String lastName private String
socialSecurityNumber private double
grossSales // gross weekly sales private
double commissionRate // commission percentage
// five-argument constructor //
constructors are NOT inherited but are implicitly
or explicitly called. // if no constructor,
the default constructor calls the superclass
constructor public CommissionEmployee( String
first, String last, String ssn, double
sales, double rate ) // implicit call
to Object default constructor occurs here
firstName first lastName last
socialSecurityNumber ssn setGrossSales(
sales ) // validate and store gross sales
setCommissionRate( rate ) // validate and store
commission rate // end five-argument
CommissionEmployee constructor
11 // set first name public void setFirstName(
String first ) firstName first
// end method setFirstName // return first
name public String getFirstName()
return firstName // end method
getFirstName // set last name public void
setLastName( String last ) lastName
last // end method setLastName //
return last name public String getLastName()
return lastName // end method
getLastName
12 // set social security number public void
setSocialSecurityNumber( String ssn )
socialSecurityNumber ssn // should validate
// end method setSocialSecurityNumber //
return social security number public String
getSocialSecurityNumber() return
socialSecurityNumber // end method
getSocialSecurityNumber // set commission
employee's gross sales amount public void
setGrossSales( double sales )
grossSales ( sales lt 0.0 ) ? 0.0 sales
// end method setGrossSales // return
commission employee's gross sales amount
public double getGrossSales() return
grossSales // end method getGrossSales
13 // set commission employee's rate public
void setCommissionRate( double rate )
commissionRate ( rate gt 0.0 rate lt 1.0 ) ?
rate 0.0 // end method setCommissionRate
// return commission employee's rate public
double getCommissionRate() return
commissionRate // end method
getCommissionRate // calculate commission
employee's pay public double earnings()
return commissionRate grossSales //
end method earnings // return String
representation of CommissionEmployee object
public String toString() return
String.format( "s s s\ns s\ns .2f\ns
.2f", "commission employee",
firstName, lastName, "social security
number", socialSecurityNumber, "gross
sales", grossSales, "commission rate",
commissionRate ) // end method toString
// end class CommissionEmployee
14- // Fig. 9.5 CommissionEmployeeTest.java.
Testing class CommissionEmployee. - public class CommissionEmployeeTest
-
- public static void main( String args )
-
- // instantiate CommissionEmployee object
- CommissionEmployee employee new
CommissionEmployee( - "Sue", "Jones", "222-22-2222", 10000,
.06 ) -
- // get commission employee data
- System.out.println( "Employee information
obtained by get methods \n" ) - System.out.printf( "s s\n", "First name
is", employee.getFirstName() ) - System.out.printf( "s s\n", "Last name
is", employee.getLastName() ) - System.out.printf( "s s\n", "Social
security number is", -
employee.getSocialSecurityNumber() ) - System.out.printf( "s .2f\n", "Gross
sales is", employee.getGrossSales() ) - System.out.printf( "s .2f\n", "Commission
rate is", employee.getCommissionRate() )
15- // Fig. 9.6 BasePlusCommissionEmployee.java
- // BasePlusCommissionEmployee class represents an
employee that receives - // a base salary in addition to commission.
- public class BasePlusCommissionEmployee //
extends Object by default -
- private String firstName
- private String lastName
- private String socialSecurityNumber
- private double grossSales // gross weekly
sales - private double commissionRate // commission
percentage - private double baseSalary // base salary per
week - // six-argument constructor
- public BasePlusCommissionEmployee( String
first, String last, - String ssn, double sales, double rate,
double salary ) -
- // implicit call to Object constructor
occurs here - firstName first
same as commissioned employee
new to this class
16- // set first name
- public void setFirstName( String first )
-
- firstName first
- // end method setFirstName
- // return first name
- public String getFirstName()
-
- return firstName
- // end method getFirstName
- // set last name
- public void setLastName( String last )
-
- lastName last
- // end method setLastName
- // return last name
17- // set social security number
- public void setSocialSecurityNumber( String
ssn ) -
- socialSecurityNumber ssn // should
validate - // end method setSocialSecurityNumber
- // return social security number
- public String getSocialSecurityNumber()
-
- return socialSecurityNumber
- // end method getSocialSecurityNumber
- // set gross sales amount
- public void setGrossSales( double sales )
-
- grossSales ( sales lt 0.0 ) ? 0.0 sales
- // end method setGrossSales
- // return gross sales amount
18- // set commission rate
- public void setCommissionRate( double rate )
-
- commissionRate ( rate gt 0.0 rate lt 1.0
) ? rate 0.0 - // end method setCommissionRate
- // return commission rate
- public double getCommissionRate()
-
- return commissionRate
- // end method getCommissionRate
- // set base salary
- public void setBaseSalary( double salary )
-
- baseSalary ( salary lt 0.0 ) ? 0.0
salary - // end method setBaseSalary
- // return base salary
19- // calculate earnings
- public double earnings()
-
- return baseSalary ( commissionRate
grossSales ) - // end method earnings
- // return String representation of
BasePlusCommissionEmployee - public String toString()
-
- return String.format(
- "s s s\ns s\ns .2f\ns
.2f\ns .2f", - "base-salaried commission employee",
firstName, lastName, - "social security number",
socialSecurityNumber, - "gross sales", grossSales, "commission
rate", commissionRate, - "base salary", baseSalary )
- // end method toString
- // end class BasePlusCommissionEmployee
20- // Fig. 9.7 BasePlusCommissionEmployeeTest.java
- // Testing class BasePlusCommissionEmployee
- public class BasePlusCommissionEmployeeTest
-
- public static void main( String args )
-
- // instantiate BasePlusCommissionEmployee
object - BasePlusCommissionEmployee employee
- new BasePlusCommissionEmployee( "Bob",
"Lewis", "333-33-3333", 5000, .04, 300 ) -
- // get base-salaried commission employee
data - System.out.println( "Employee information
obtained by get methods \n" ) - System.out.printf( "s s\n", "First name
is", employee.getFirstName() ) - System.out.printf( "s s\n", "Last name
is", employee.getLastName() ) - System.out.printf( "s s\n", "Social
security number is", - employee.getSocialSecurityNumber() )
- System.out.printf( "s .2f\n", "Gross
sales is", employee.getGrossSales() ) - System.out.printf( "s .2f\n", "Commission
rate is",
21- // Fig. 9.8 BasePlusCommissionEmployee2.java
- // BasePlusCommissionEmployee2 inherits from
class CommissionEmployee. - public class BasePlusCommissionEmployee2 extends
CommissionEmployee -
- private double baseSalary // base salary per
week - // six-argument constructor
- public BasePlusCommissionEmployee2( String
first, String last, - String ssn, double sales, double rate,
double salary ) -
- // explicit call to superclass
CommissionEmployee constructor - super( first, last, ssn, sales, rate )
- setBaseSalary( salary ) // validate and
store base salary - // end six-argument BasePlusCommissionEmploye
e2 constructor -
- // set base salary
- public void setBaseSalary( double salary )
inheritance
just need to declare new field
22- // return base salary
- public double getBaseSalary()
-
- return baseSalary
- // end method getBaseSalary
- // calculate earnings
- public double earnings()
-
- // not allowed commissionRate and
grossSales private in superclass - return baseSalary ( commissionRate
grossSales ) - // end method earnings
- // return String representation of
BasePlusCommissionEmployee2 - public String toString()
-
- // not allowed attempts to access private
superclass members - return String.format(
23- // Fig. 9.9 CommissionEmployee2.java
- // CommissionEmployee2 class represents a
commission employee. - public class CommissionEmployee2
-
- protected String firstName
- protected String lastName
- protected String socialSecurityNumber
- protected double grossSales // gross weekly
sales - protected double commissionRate // commission
percentage - // five-argument constructor
- public CommissionEmployee2( String first,
String last, String ssn, - double sales, double rate )
-
- // implicit call to Object constructor
occurs here - firstName first
- lastName last
use protected fields
24- // set first name
- public void setFirstName( String first )
-
- firstName first
- // end method setFirstName
- // return first name
- public String getFirstName()
-
- return firstName
- // end method getFirstName
- // set last name
- public void setLastName( String last )
-
- lastName last
- // end method setLastName
- // return last name
25- // set social security number
- public void setSocialSecurityNumber( String
ssn ) -
- socialSecurityNumber ssn // should
validate - // end method setSocialSecurityNumber
- // return social security number
- public String getSocialSecurityNumber()
-
- return socialSecurityNumber
- // end method getSocialSecurityNumber
- // set gross sales amount
- public void setGrossSales( double sales )
-
- grossSales ( sales lt 0.0 ) ? 0.0 sales
- // end method setGrossSales
- // return gross sales amount
26- // set commission rate
- public void setCommissionRate( double rate )
-
- commissionRate ( rate gt 0.0 rate lt 1.0
) ? rate 0.0 - // end method setCommissionRate
- // return commission rate
- public double getCommissionRate()
-
- return commissionRate
- // end method getCommissionRate
- // calculate earnings
- public double earnings()
-
- return commissionRate grossSales
- // end method earnings
- // return String representation of
CommissionEmployee2 object
27- // Fig. 9.10 BasePlusCommissionEmployee3.java
- // BasePlusCommissionEmployee3 inherits from
CommissionEmployee2 and has - // access to CommissionEmployee2's protected
members. - public class BasePlusCommissionEmployee3 extends
CommissionEmployee2 -
- private double baseSalary // base salary per
week - // six-argument constructor
- public BasePlusCommissionEmployee3( String
first, String last, - String ssn, double sales, double rate,
double salary ) -
- super( first, last, ssn, sales, rate )
- setBaseSalary( salary ) // validate and
store base salary - // end six-argument BasePlusCommissionEmploye
e3 constructor -
- // set base salary
- public void setBaseSalary( double salary )
inheritance
just need to declare new field, can
access protected members of superclass
explicit constructor call base class doesnt have
default constructor to call implicitly
28- // return base salary
- public double getBaseSalary()
-
- return baseSalary
- // end method getBaseSalary
- // calculate earnings
- public double earnings()
-
- return baseSalary ( commissionRate
grossSales ) - // end method earnings
- // return String representation of
BasePlusCommissionEmployee3 - public String toString()
-
- return String.format(
- "s s s\ns s\ns .2f\ns
.2f\ns .2f", - "base-salaried commission employee",
firstName, lastName, - "social security number",
socialSecurityNumber,
notice how much less code there is due to
inheritance
29- // Fig. 9.11 BasePlusCommissionEmployeeTest3.java
- // Testing class BasePlusCommissionEmployee3.
- public class BasePlusCommissionEmployeeTest3
-
- public static void main( String args )
-
- // instantiate BasePlusCommissionEmployee3
object - BasePlusCommissionEmployee3
basePlusCommissionEmployee - new BasePlusCommissionEmployee3(
- "Bob", "Lewis", "333-33-3333", 5000,
.04, 300 ) -
- // get base-salaried commission employee
data - System.out.println( "Employee information
obtained by get methods \n" ) - System.out.printf( "s s\n", "First name
is", - basePlusCommissionEmployee.getFirstName()
) - System.out.printf( "s s\n", "Last name
is", - basePlusCommissionEmployee.getLastName()
) - System.out.printf( "s s\n", "Social
security number is",
30- basePlusCommissionEmployee.setBaseSalary(
1000 ) // set base salary -
- System.out.printf( "\ns\n\ns\n",
- "Updated employee information obtained
by toString", - basePlusCommissionEmployee.toString() )
- // end main
- // end class BasePlusCommissionEmployeeTest3
31Protected Instance Variables
- Our textbook recommends using private superclass
variables rather than protected. - This forces the subclass to use the get and set
methods of the superclass. - This is better since any validation or
formatting/conversion is not bypassed. - The next example takes this approach.
32- // Fig. 9.12 CommissionEmployee3.java
- // CommissionEmployee3 class represents a
commission employee. - public class CommissionEmployee3
-
- private String firstName
- private String lastName
- private String socialSecurityNumber
- private double grossSales // gross weekly
sales - private double commissionRate // commission
percentage - // five-argument constructor
- public CommissionEmployee3( String first,
String last, String ssn, - double sales, double rate )
-
- // implicit call to Object constructor
occurs here - firstName first
- lastName last
- socialSecurityNumber ssn
use private fields
33- // set first name
- public void setFirstName( String first )
-
- firstName first
- // end method setFirstName
- // return first name
- public String getFirstName()
-
- return firstName
- // end method getFirstName
- // set last name
- public void setLastName( String last )
-
- lastName last
- // end method setLastName
- // return last name
34- // set social security number
- public void setSocialSecurityNumber( String
ssn ) -
- socialSecurityNumber ssn // should
validate - // end method setSocialSecurityNumber
- // return social security number
- public String getSocialSecurityNumber()
-
- return socialSecurityNumber
- // end method getSocialSecurityNumber
- // set gross sales amount
- public void setGrossSales( double sales )
-
- grossSales ( sales lt 0.0 ) ? 0.0 sales
- // end method setGrossSales
- // return gross sales amount
35- // set commission rate
- public void setCommissionRate( double rate )
-
- commissionRate ( rate gt 0.0 rate lt 1.0
) ? rate 0.0 - // end method setCommissionRate
- // return commission rate
- public double getCommissionRate()
-
- return commissionRate
- // end method getCommissionRate
- // calculate earnings
- public double earnings()
-
- return getCommissionRate()
getGrossSales() - // end method earnings
- // return String representation of
CommissionEmployee3 object
36- // Fig. 9.13 BasePlusCommissionEmployee4.java
- // BasePlusCommissionEmployee4 class inherits
from CommissionEmployee3 and - // accesses CommissionEmployee3's private data
via CommissionEmployee3's - // public methods.
- public class BasePlusCommissionEmployee4 extends
CommissionEmployee3 -
- private double baseSalary // base salary per
week - // six-argument constructor
- public BasePlusCommissionEmployee4( String
first, String last, - String ssn, double sales, double rate,
double salary ) -
- super( first, last, ssn, sales, rate )
- setBaseSalary( salary ) // validate and
store base salary - // end six-argument BasePlusCommissionEmploye
e4 constructor -
- // set base salary
- public void setBaseSalary( double salary )
inheritance
just need to declare new field, can
access private members of superclass
with get/set methods
37- // return base salary
- public double getBaseSalary()
-
- return baseSalary
- // end method getBaseSalary
- // calculate earnings
- public double earnings()
-
- return getBaseSalary() super.earnings()
- // end method earnings
- // return String representation of
BasePlusCommissionEmployee4 - public String toString()
-
- return String.format( "s s\ns .2f",
"base-salaried", - super.toString(), "base salary",
getBaseSalary() ) - // end method toString
38- // Fig. 9.14 BasePlusCommissionEmployeeTest4.java
- // Testing class BasePlusCommissionEmployee4.
- public class BasePlusCommissionEmployeeTest4
-
- public static void main( String args )
-
- // instantiate BasePlusCommissionEmployee4
object - BasePlusCommissionEmployee4 employee
- new BasePlusCommissionEmployee4(
- "Bob", "Lewis", "333-33-3333", 5000,
.04, 300 ) -
- // get base-salaried commission employee
data - System.out.println(
- "Employee information obtained by get
methods \n" ) - System.out.printf( "s s\n", "First name
is", - employee.getFirstName() )
- System.out.printf( "s s\n", "Last name
is", - employee.getLastName() )
39- System.out.printf( "s .2f\n", "Commission
rate is", - employee.getCommissionRate() )
- System.out.printf( "s .2f\n", "Base
salary is", - employee.getBaseSalary() )
- employee.setBaseSalary( 1000 ) // set base
salary -
- System.out.printf( "\ns\n\ns\n",
- "Updated employee information obtained
by toString", - employee.toString() )
- // end main
- // end class BasePlusCommissionEmployeeTest4
40- // Fig. 9.15 CommissionEmployee4.java,
demonstrates constructor calls - // CommissionEmployee4 class represents a
commission employee. - public class CommissionEmployee4
-
- private String firstName
- private String lastName
- private String socialSecurityNumber
- private double grossSales // gross weekly
sales - private double commissionRate // commission
percentage - // five-argument constructor
- public CommissionEmployee4( String first,
String last, String ssn, - double sales, double rate )
-
- // implicit call to Object constructor
occurs here - firstName first
- lastName last
prints message when constructor is called
41- // set first name
- public void setFirstName( String first )
-
- firstName first
- // end method setFirstName
- // return first name
- public String getFirstName()
-
- return firstName
- // end method getFirstName
- // set last name
- public void setLastName( String last )
-
- lastName last
- // end method setLastName
- // return last name
42- // set social security number
- public void setSocialSecurityNumber( String
ssn ) -
- socialSecurityNumber ssn // should
validate - // end method setSocialSecurityNumber
- // return social security number
- public String getSocialSecurityNumber()
-
- return socialSecurityNumber
- // end method getSocialSecurityNumber
- // set gross sales amount
- public void setGrossSales( double sales )
-
- grossSales ( sales lt 0.0 ) ? 0.0 sales
- // end method setGrossSales
- // return gross sales amount
43- // set commission rate
- public void setCommissionRate( double rate )
-
- commissionRate ( rate gt 0.0 rate lt 1.0
) ? rate 0.0 - // end method setCommissionRate
- // return commission rate
- public double getCommissionRate()
-
- return commissionRate
- // end method getCommissionRate
- // calculate earnings
- public double earnings()
-
- return getCommissionRate()
getGrossSales() - // end method earnings
- // return String representation of
CommissionEmployee4 object
44- // Fig. 9.16 BasePlusCommissionEmployee5.java,
demonstrates constructor calls - // BasePlusCommissionEmployee5 class declaration.
- public class BasePlusCommissionEmployee5 extends
CommissionEmployee4 -
- private double baseSalary // base salary per
week - // six-argument constructor
- public BasePlusCommissionEmployee5( String
first, String last, - String ssn, double sales, double rate,
double salary ) -
- super( first, last, ssn, sales, rate )
- setBaseSalary( salary ) // validate and
store base salary -
- System.out.printf(
- "\nBasePlusCommissionEmployee5
constructor\ns\n", this ) - // end six-argument BasePlusCommissionEmploye
e5 constructor -
- // set base salary
prints message when constructor is called
45- // return base salary
- public double getBaseSalary()
-
- return baseSalary
- // end method getBaseSalary
- // calculate earnings
- public double earnings()
-
- return getBaseSalary() super.earnings()
- // end method earnings
- // return String representation of
BasePlusCommissionEmployee5 - public String toString()
-
- return String.format( "s s\ns .2f",
"base-salaried", - super.toString(), "base salary",
getBaseSalary() ) - // end method toString
- // end class BasePlusCommissionEmployee5
46- // Fig. 9.17 ConstructorTest.java, demonstrates
constructor calls - // Display order in which superclass and subclass
constructors are called. - public class ConstructorTest
-
- public static void main( String args )
-
- CommissionEmployee4 employee1 new
CommissionEmployee4( - "Bob", "Lewis", "333-33-3333", 5000, .04
) -
- System.out.println()
- BasePlusCommissionEmployee5 employee2
- new BasePlusCommissionEmployee5(
- "Lisa", "Jones", "555-55-5555", 2000,
.06, 800 ) -
- System.out.println()
- BasePlusCommissionEmployee5 employee3
- new BasePlusCommissionEmployee5(
- "Mark", "Sands", "888-88-8888", 8000,
.15, 2000 )
47- CommissionEmployee4 constructor
- commission employee Bob Lewis
- social security number 333-33-3333
- gross sales 5000.00
- commission rate 0.04
- CommissionEmployee4 constructor
- base-salaried commission employee Lisa Jones
- social security number 555-55-5555
- gross sales 2000.00
- commission rate 0.06
- base salary 0.00
- CommissionEmployee5 constructor
- base-salaried commission employee Lisa Jones
- social security number 555-55-5555
- gross sales 2000.00
- commission rate 0.06
- CommissionEmployee4 constructor
- base-salaried commission employee Mark Sands
- social security number 888-88-8888
- gross sales 8000.00
- commission rate 0.15
- base salary 0.00
- CommissionEmployee5 constructor
- base-salaried commission employee Lisa Jones
- social security number 888-88-8888
- gross sales 8000.00
- commission rate 0.15
- base salary 2000.00
48Inheritance
- Inheritance may be performed without access to
the superclass source file. - Java simply requires access to the .class file.
- This is good for independent software vendors
(ISVs) who do not wish to expose their
sourcecode. - Having the sourcecode is usually best so you can
inspect and evaluate it.
49Inheritance
- Reading subclass declarations can be confusing
because the sourcecode being called exists in the
superclass. - Documentation can be difficult to do for this
reason as well.
50Object Class Methods
51Graphics
- Displaying labels can be accomplished with class
JLabel. - JLabel.BorderLayout contains constants for 5
regions of the frame NORTH, SOUTH, EAST, WEST,
CENTER - Class ImageIcon lets an image be displayed on a
label. - Method setText changes text on a label.
52- // Fig 9.19 LabelDemo.java
- // Demonstrates the use of labels.
- import java.awt.BorderLayout
- import javax.swing.ImageIcon
- import javax.swing.JLabel
- import javax.swing.JFrame
- public class LabelDemo
-
- public static void main( String args )
-
- // Create a label with plain text
- JLabel northLabel new JLabel( "North" )
-
- // create an icon from an image so we can
put it on a JLabel - ImageIcon labelIcon new ImageIcon(
"GUItip.gif" ) -
- // create a label with an Icon instead of
text - JLabel centerLabel new JLabel( labelIcon
)
53- // create a frame to hold the labels
- JFrame application new JFrame()
-
- application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE ) - // add the labels to the frame the second
argument specifies - // where on the frame to add the label
- application.add( northLabel,
BorderLayout.NORTH ) - application.add( centerLabel,
BorderLayout.CENTER ) - application.add( southLabel,
BorderLayout.SOUTH ) - application.setSize( 300, 300 ) // set the
size of the frame - application.setVisible( true ) // show the
frame - // end main
- // end class LabelDemo
54(No Transcript)
55End of Slides