0% found this document useful (0 votes)
6 views39 pages

Understanding Inheritance in Java Classes

The document discusses the concept of inheritance in object-oriented programming, emphasizing software reusability through the creation of subclasses from superclasses. It outlines the relationships between superclasses and subclasses, including single and multiple inheritance, and provides examples of class hierarchies. Additionally, it covers common programming errors related to method overriding and constructor calls in subclasses.

Uploaded by

amnaaurangzeb95
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views39 pages

Understanding Inheritance in Java Classes

The document discusses the concept of inheritance in object-oriented programming, emphasizing software reusability through the creation of subclasses from superclasses. It outlines the relationships between superclasses and subclasses, including single and multiple inheritance, and provides examples of class hierarchies. Additionally, it covers common programming errors related to method overriding and constructor calls in subclasses.

Uploaded by

amnaaurangzeb95
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction

 Inheritance
 Software reusability
 Create new class from existing class
 Absorb existing class’s data and behaviors
 Enhance with new capabilities
 Subclass extends superclass
 Subclass
 More specialized group of objects

 Behaviors inherited from superclass

 Can customize

 Additional behaviors

2
Introduction (Cont.)
 Class hierarchy
 Direct superclass
 Inherited explicitly (one level up hierarchy)
 Indirect superclass
 Inherited two or more levels up hierarchy
 Single inheritance
 Inherits from one superclass
 Multiple inheritance
 Inherits from multiple superclasses
 Java does not support multiple inheritance

3
Superclasses and subclasses
 Superclasses and subclasses
 Object of one class “is an” object of another class
 Example: Rectangle is quadrilateral.
 Class Rectangle inherits from class Quadrilateral

 Quadrilateral: superclass

 Rectangle: subclass

 Superclass typically represents larger set of objects than subclasses


 Example:
 superclass: Vehicle

 subclass: Car

 Smaller, more-specific subset of vehicles

4
Superclass Subclasses
Student GraduateStudent, UndergraduateStudent
Shape Circle, Triangle, Rectangle
Loan CarLoan, HomeImprovementLoan,
MortgageLoan
Employee Faculty, Staff
BankAccount CheckingAccount, SavingsAccount

Fig. 9.1 | Inheritance examples.

5
Superclasses and subclasses (Cont.)
 Inheritance hierarchy
 Inheritance relationships: tree-like hierarchy structure
 Each class becomes
 superclass
 Supply members to other classes

OR
 subclass
 Inherit members from other classes

6
Fig. 9.2 | Inheritance hierarchy for university CommunityMembers

7
Fig. 9.3 | Inheritance hierarchy for Shapes.

8
Relationship between Superclasses and Subclasses

 Superclass and subclass relationship


 Example:
CommissionEmployee/BasePlusCommissionEmployee
inheritance hierarchy
 CommissionEmployee
 First name, last name, SSN, commission rate, gross sale
amount
 BasePlusCommissionEmployee
 First name, last name, SSN, commission rate, gross sale
amount
 Base salary

9
Creating and Using a CommissionEmployee Class

 Class CommissionEmployee
 Extends class Object
 Keyword extends
 Every class in Java extends an existing class
 Except Object

 Every class inherits Object’s methods


 New class implicitly extends Object
 If it does not extend another class

10
Common Programming Error 9.1
 It is a syntax error to override a method with a more
restricted access modifier—a public method of
the superclass cannot become a protected or
private method in the subclass; a protected
method of the superclass cannot become a
private method in the subclass. Doing so would
break the “is-a” relationship in which it is required
that all subclass objects be able to respond to
method calls that are made to public methods
declared in the superclass.(cont…)

11
Common Programming Error 9.1
 If a public method could be overridden as a
protected or private method, the subclass
objects would not be able to respond to the same
method calls as superclass objects. Once a method
is declared public in a superclass, the method
remains public for all that class’s direct and
indirect subclasses.

12
protected Members
 protected access
 Intermediate level of protection between public and
private
 protected members accessible by
 superclass members
 subclass members
 Subclass access to superclass member
 Keyword super and a dot (.)

13
CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using protected
Instance Variables

 Use protected instance variables


 Enable class BasePlusCommissionEmployee to
directly access superclass instance variables
 Superclass’s protected members are inherited by all
subclases of that superclass

14
1
2
3
// Fig. 9.12: [Link]
// CommissionEmployee3 class represents a commission employee. Outline 15

4 public class CommissionEmployee3


5 { Declare private
6
7
private String firstName;
private String lastName;
instance variables  Commission
8 private String socialSecurityNumber;  [Link]
9 private double grossSales; // gross weekly sales
10 private double commissionRate; // commission percentage  (1 of 4)
11
 Lines 6-10
12 // five-argument constructor
13 public CommissionEmployee3( String first, String last, String ssn,
14 double sales, double rate )
15 {
16 // implicit call to Object constructor occurs here
17 firstName = first;
18 lastName = last;
19 socialSecurityNumber = ssn;
20 setGrossSales( sales ); // validate and store gross sales
21 setCommissionRate( rate ); // validate and store commission rate
22 } // end five-argument CommissionEmployee3 constructor
23
24 // set first name
25 public void setFirstName( String first )
26 {
27 firstName = first;
28 } // end method setFirstName
29
30
31
32
// return first name
public String getFirstName()
{
Outline 16

33 return firstName;
34 } // end method getFirstName
35
 Commission
36 // set last name
 [Link]
37 public void setLastName( String last )
38 {
 (2 of 4)
39 lastName = last;
40 } // end method setLastName
41
42 // return last name
43 public String getLastName()
44 {
45 return lastName;
46 } // end method getLastName
47
48 // set social security number
49 public void setSocialSecurityNumber( String ssn )
50 {
51 socialSecurityNumber = ssn; // should validate
52 } // end method setSocialSecurityNumber
53
54 // return social security number
55 public String getSocialSecurityNumber()
56 {
57 return socialSecurityNumber;
58 } // end method getSocialSecurityNumber
59
60
61
62
// set gross sales amount
public void setGrossSales( double sales )
{
Outline 17

63 grossSales = ( sales < 0.0 ) ? 0.0 : sales;


64 } // end method setGrossSales
65  Commission
66 // return gross sales amount  [Link]
67 public double getGrossSales()
68 {  (3 of 4)
69 return grossSales;
70 } // end method getGrossSales
71
72 // set commission rate
73 public void setCommissionRate( double rate )
74 {
75 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
76 } // end method setCommissionRate
77
78 // return commission rate
79 public double getCommissionRate()
80 {
81 return commissionRate;
82 } // end method getCommissionRate
83
84
85
86
// calculate earnings
public double earnings()
{
Outline 18

87 return getCommissionRate() * getGrossSales();


88 } // end method earnings
89 Use get methods to
90 // return String representation of CommissionEmployee3obtain
object the values of
 Commission
91 public String toString()
instance variables  [Link]
92 {
93 return [Link]( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f",  (4 of 4)
94 "commission employee", getFirstName(), getLastName(),
 Line 87
95 "social security number", getSocialSecurityNumber(),
96 "gross sales", getGrossSales(),  Lines 94-97
97 "commission rate", getCommissionRate() );
98 } // end method toString
99 } // end class CommissionEmployee3
1
2
3
// Fig. 9.13: [Link]
// BasePlusCommissionEmployee4 class inherits from CommissionEmployee3 and
// accesses CommissionEmployee3's private data via CommissionEmployee3's
Outline 19

4 // public methods.
5
6 public class BasePlusCommissionEmployee4 extends CommissionEmployee3
 BasePlusCommiss
7 {
[Link]
8
9
private double baseSalary; // base salary per week
Inherits from a
10 // six-argument constructor
 (1 of 2)
CommissionEmploye
11 e3
public BasePlusCommissionEmployee4( String first, String last,
12 String ssn, double sales, double rate, double salary )
13 {
14 super( first, last, ssn, sales, rate );
15 setBaseSalary( salary ); // validate and store base salary
16 } // end six-argument BasePlusCommissionEmployee4 constructor
17
18 // set base salary
19 public void setBaseSalary( double salary )
20 {
21 baseSalary = ( salary < 0.0 ) ? 0.0 : salary;
22 } // end method setBaseSalary
23
24
25
26
// return base salary
public double getBaseSalary()
{
Outline 20

27 return baseSalary;
28 } // end method getBaseSalary
29
30 // calculate earnings
Invoke an overridden
 BasePlusCom
31 public double earnings() superclass method from a
missionEmplo
32 { subclass [Link]
33 return getBaseSalary() + [Link]();
34 } // end method earnings  (2 of 2)
35 Use get methods  toLine 33 & 40
36
obtain the values of
// return String representation of BasePlusCommissionEmployee4
37 public String toString()  Line 33
38 {
instance variables
39 return [Link]( "%s %s\n%s: %.2f", "base-salaried",
 Lines 40
40 [Link](), "base salary", getBaseSalary() );
41 } // end method toString
42 } // end class BasePlusCommissionEmployee4 Invoke an overridden
superclass method from a
subclass
Common Programming Error 9.3
 When a superclass method is overridden in a
subclass, the subclass version often calls the
superclass version to do a portion of the work.
Failure to prefix the superclass method name with
the keyword super and a dot (.) separator when
referencing the superclass’s method causes the
subclass method to call itself, creating an error
called infinite recursion.

21
1
2
3
// Fig. 9.14: [Link]
// Testing class BasePlusCommissionEmployee4. Outline 22

4 public class BasePlusCommissionEmployeeTest4


5 {
6
7
public static void main( String args[] )
{ Create  BasePlusCo
8 // instantiate BasePlusCommissionEmployee4 object mmissionE
BasePlusCommissionEmployee4
9 BasePlusCommissionEmployee4 employee =
object. mployeeTest
10
11
new BasePlusCommissionEmployee4(
"Bob", "Lewis", "333-33-3333", 5000, .04, 300 );
[Link]
12
 (1 of 2)
13 // get base-salaried commission employee data
 Lines 9-11
14 [Link](
 Lines 16-25
15 "Employee information obtained by get methods: \n" );
16 [Link]( "%s %s\n", "First name is",
17 [Link]() );
18 [Link]( "%s %s\n", "Last name is",
19 [Link]() );
20 [Link]( "%s %s\n", "Social security number is", Use inherited get
21 [Link]() ); methods to access
22 [Link]( "%s %.2f\n", "Gross sales is",
inherited private
23 [Link]() );
24 [Link]( "%s %.2f\n", "Commission rate is", instance variables
25 [Link]() );
26 [Link]( "%s %.2f\n", "Base salary is",
27 [Link]() ); Use BasePlusCommissionEmployee4 get
28 method to access private instance
variable.
29
30
31
[Link]( 1000 ); // set base salary

[Link]( "\n%s:\n\n%s\n",
Outline 23

32
Use BasePlusCommissionEmployee4 set
"Updated employee information obtained by toString",
33 [Link]() ); method to modify private instance variable
34 } // end main baseSalary.  BasePlusCommiss
35 } // end class BasePlusCommissionEmployeeTest4 ionEmployeeTest4
.java
Employee information obtained by get methods:
 (2 of 2)
First name is Bob
Last name is Lewis
Social security number is 333-33-3333
Gross sales is 5000.00
Commission rate is 0.04
Base salary is 300.00
Updated employee information obtained by toString:

base-salaried commission employee: Bob Lewis


social security number: 333-33-3333
gross sales: 5000.00
commission rate: 0.04
base salary: 1000.00
Software Engineering Observation 9.8
 When a program creates a subclass object, the
subclass constructor immediately calls the
superclass constructor (explicitly, via super, or
implicitly).
 The superclass constructor’s body executes to
initialize the superclass’s instance variables that are
part of the subclass object, then the subclass
constructor’s body executes to initialize the
subclass-only instance variables

25
Constructors in Subclasses
 Instantiating subclass object
 Chain of constructor calls
 subclass constructor invokes superclass constructor
 Implicitly or explicitly

 Base of inheritance hierarchy


 Last constructor called in chain is Object’s constructor

 Original subclass constructor’s body finishes executing last

26
Fig. 9.2 | Inheritance hierarchy for university CommunityMembers

27
Software Engineering Observation 9.8
 Java ensures that even if a constructor does not
assign a value to an instance variable, the variable is
still initialized to its default value (e.g., 0 for
primitive numeric types, false for booleans, null
for references).

28
Constructor Calls…
 There are some restrictions on how you can use the
base class constructor call super .
 Also, the call to the base class constructor ( super )
must always be the first action taken in a
constructor definition. You cannot use it later in the
definition of a constructor.
 Notice that you use the keyword super to call the
constructor of the base class. You do not use the
name of the constructor; you do not use
 Employee(theName, theDate); //ILLEGAL

29
Constructor Calls…
 If a constructor definition for a derived class does not
include an invocation of a constructor for the base
class, then the no-argument constructor of the base
class is invoked automatically as the first action of the
derived class constructor.
 Within the definition of a constructor for a class, you
can use super as a name for a constructor of the base
class. Any invocation of super must be the first action
taken by the constructor.
 EXAMPLE
 public SalariedEmployee(SalariedEmployee
originalObject)
{
 super(originalObject);
 salary = [Link];
}
Software Engineering Observation 9.10
 At the design stage in an object-oriented system,
the designer often finds that certain classes are
closely related. The designer should “factor out”
common instance variables and methods and place
them in a superclass. Then the designer should use
inheritance to develop subclasses, specializing them
with capabilities beyond those inherited from the
superclass.

32
Notes
 The inherited fields can be used directly, just like any other
fields.
 You can declare a field in the subclass with the same name
as the one in the superclass, thus hiding it (not
recommended).
 You can declare new fields in the subclass that are not in
the superclass.
 The inherited methods can be used directly as they are.
 You can write a new instance method in the subclass that
has the same signature as the one in the superclass,
thus overriding it.
 You can declare new methods in the subclass that are not
in the superclass.
 You can write a subclass constructor that invokes the
constructor of the superclass, either implicitly or by using
the keyword super.
Notes
 A subclass does not inherit the private members of its
parent class. However, if the superclass has public or
protected methods for accessing its private fields,
these can also be used by the subclass.
Object Class
 All classes in java inherit directly or indirectly from the
Object class (package [Link])
 Class Object methods
 clone
 equals
 finalize
 getClass
 hashCode
 notify, notifyAll, wait
 toString

35
An Object of a Derived Class Has
More than One Type
 An object of a derived class has the type of the derived
class, and it also has the type of the base class.
 More generally, a derived class has the type of every one of
its ancestor classes.
 So, you can assign an object of a derived class to a variable
of any ancestor type (but not the other way around).
 You can plug in a derived class object for a parameter of any
of its ancestor types.
 More generally, you can use a derived class object anyplace
you can use an object of any of its ancestor types.
Private Methods Are Effectively
Not Inherited
 The private methods of the base class are just like
private variables in terms of not being directly
available.
Acknowledgements
 Deitel, Java How to Program

You might also like