Chapter FOUR
OOP:- Inheritance
1
What is Inheritance?
In the real world: We inherit behaviors from our
mother and father. We also inherit traits from
our grandmother, grandfather, and ancestors.
We might have similar eyes, the same smile, a
different height. weight . . . but we are in many
ways "derived" from our parents.
In software: Object inheritance is more well
defined! Objects that are derived from other
object "resemble" their parents by inheriting
both state (fields) and behavior (methods).
2
Dog Class
public class Dog {
private String name;
private int fleas;
public Dog(String n, int f) {
name = n;
fleas = f;
}
public String getName() { return name; }
public int getFleas() { return fleas; }
public void speak() {
[Link]("Woof");
}
} 3
Cat Class
public class Cat {
private String name;
private int hairballs;
public Cat(String n, int h) {
name = n;
hairballs = h;
}
public String getName() { return name; }
public int getHairballs() { return hairballs; }
public void speak() {
[Link]("Meow");
}
} 4
Problem: Code Duplication
• Dog and Cat have the name field and
the getName method in common
• Classes often have a lot of state and
behavior in common
• Result: lots of duplicate code!
5
Solution: Inheritance
• Inheritance allows you to write new classes
that inherit from existing classes
• The existing class whose properties are
inherited is called the "parent" or superclass
• The new class that inherits from the super
class is called the "child" or subclass
• Result: Lots of code reuse!
6
Dog Cat
String name String name
int fleas int hairballs
String getName() String getName()
int getFleas() int getHairballs()
void speak() void speak()
using
inheritance
superclass
Animal
subclass
String name
subclass String getName()
Dog Cat
int fleas int hairballs
int getFleas() int getHairballs()
void speak() void speak() 7
Animal Superclass
public class Animal {
private String name;
public Animal(String n) {
name = n;
}
public String getName() {
return name;
}
}
8
Dog Subclass
public class Dog extends Animal {
private int fleas;
public Dog(String n, int f) {
super(n); // calls Animal constructor
fleas = f;
}
public int getFleas() {
return fleas;
}
public void speak() {
[Link]("Woof");
}
} 9
Cat Subclass
public class Cat extends Animal {
private int hairballs;
public Cat(String n, int h) {
super(n); // calls Animal constructor
hairballs = h;
}
public int getHairballs() {
return hairballs;
}
public void speak() {
[Link]("Meow");
}
} 10
Inheritance Quiz 1
• What is the output of the following?
Dog d = new Dog(“Boby“, 3);
Cat c = new Cat(“Urro", 2);
[Link]([Link]() + " has " +
[Link]() + " fleas");
[Link]([Link]() + " has " +
[Link]() + " hairballs");
Boby has 3 fleas
Urro has 2 hairballs
(Dog and Cat inherit the getName method from Animal) 11
Inheritance Rules
• Use the extends keyword to indicate that
one class inherits from another
• The subclass inherits all the fields and
methods of the superclass
• Use the super keyword in the subclass
constructor to call the superclass constructor
12
Subclass Constructor
• The first thing a subclass constructor must do
is call the superclass constructor
• This ensures that the superclass part of the
object is constructed before the subclass part
• If you do not call the superclass constructor
with the super keyword, and the superclass
has a constructor with no arguments, then that
superclass constructor will be called implicitly.
13
Implicit Super Constructor Call
then this Beef subclass:
public class Beef extends Food {
If I have this Food class: private double weight;
public Beef(double w) {
public class Food { weight = w
private boolean raw; }
public Food() { }
raw = true;
} is equivalent to:
}
public class Beef extends Food {
private double weight;
public Beef(double w) {
super();
weight = w
}
} 14
Inheritance Quiz 2
public class A {
int Z;
public A() {
[Link]("I'm A");
Z=10;
}
}
public class B extends A {
public B() {
[Link]("I'm B");
Z=15;
}
}
public class C extends B {
public C() {
[Link]("I'm C");
Z=45;
}
} I'm A
What does this print out? I'm B
C x = new C();
I'm C 15
[Link](x.Z);
45
Overriding Methods
• Subclasses can override methods in their superclass
class Therm { class ThermUS extends Therm {
public double celsius;
public ThermUS(double c) {
public Therm(double c) { super(c);
celsius = c; }
}
// degrees in Fahrenheit
public double getTemp() { public double getTemp() {
return celcius; return celsius * 1.8 + 32;
} }
} }
• What is the output of the following? 212
ThermUS thermometer = new ThermUS(100);
[Link]([Link]());16
Calling Superclass Methods
• When you override a method, you can call
the superclass's copy of the method by
using the syntax [Link]()
class Therm { class ThermUS extends Therm {
private double celsius;
public ThermUS(double c) {
public Therm(double c) { super(c);
celcius = c; }
}
public double getTemp() {
public double getTemp() { return [Link]()
return celcius; * 1.8 + 32;
} }
} } 17
Access Level
Classes can contain fields and methods of four different
access levels:
•Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
•package : The access level of a default modifier is only within
the package. It cannot be accessed from outside the package.
If you do not specify any access level, it will be the default.
•Protected: The access level of a protected modifier is within
the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from
outside the package.
•Public: The access level of a public modifier is everywhere. It
can be accessed from within the class, outside the class,
within the package and outside the package. 18
For Fields
Access Modifier For Classes For Methods
(Variables)
public ✔ Yes ✔ Yes ✔ Yes
protected ❌ No ✔ Yes ✔ Yes
default (no ✔ Yes (package-
✔ Yes ✔ Yes
modifier) private class)
❌ No (only inner
private ✔ Yes ✔ Yes
classes allowed)
the package keyword is never used in front of a class, method,
or field to control access.
19
Variable Type vs Object Type
• Variables have the types they are given when
they are declared and objects have the type of
their class.
• For an object to be assigned to a variable is
must be of the same class or a subclass of
the type of the variable.
• You may not call a method on a variable if it's
type does not have that method, even if the
object it references has the method.
20
Dog
Which Lines Don't Compile? String name
int fleas
public static void main(String[] args) { String getName()
Animal a1 = new Animal(); int getFleas()
void speak()
[Link]();
[Link](); // Animal does not have getFleas
[Link](); // Animal does not have getHairballs
[Link](); // Animal does not have speak
Animal a2 = new Dog();
[Link]();
[Link](); // Animal does not have getFleas
[Link](); // Animal does not have getHairballs
[Link](); // Animal does not have speak
Dog d = new Dog(); Cat
[Link](); String name
[Link](); int hairballs
[Link](); // Dog does not have getHairballs
String getName()
[Link](); int getHairballs(
} void speak()
21
Programming Example
• A Company has a list of Employees. It asks you
to provide a payroll sheet for all employees.
– Has extensive data (name, department, pay
amount, …) for all employees.
– Different types of employees – manager,
engineer, software engineer.
– You have an old Employee class but need to add
very different data and methods for managers
and engineers.
• Suppose someone wrote a name system, and already
provided a legacy Employee class. The old Employee
class had a printData() method for each Employee that
only printed the name. We want to reuse it, and print
pay info. 22
REVIEW PICTURE
Encapsulation Message passing "Main event loop"
Employee e1 public … Main(…){
printData Employee e1…
(“Abebech",“Gobena");
private: ...
lastName [Link]();
firstName
// Prints Employee names.
...
}
23
Employee class
This is a simple super or base class.
class Employee {
// Data
private String firstName, lastName;
// Constructor
public Employee(String fName, String lName) {
firstName= fName; lastName= lName;
}
// Method
public void printData() {
[Link](firstName + " " + lastName);}
}
24
Inheritance
Already written:
Class Employee
firstName printData()
lastName
is-a is-a
Class Engineer
Class Manager
firstName firstName
lastName lastName
hoursWorked
salary
printData() wages
getPay()
printData()
getPay()
You next write: 25
Engineer class
Subclass or (directly) derived class
class Engineer extends Employee {
private double wage;
private double hoursWorked;
public Engineer(String fName, String lName,
double rate, double hours) {
super(fName, lName);
wage = rate;
hoursWorked = hours;
}
public double getPay() {
return wage * hoursWorked;
}
public void printData() {
[Link](); // PRINT NAME
[Link]("Weekly pay: $" +
getPay()); } 26
}
Manager class
Subclass or (directly) derived class
class Manager extends Employee {
private double salary;
public Manager(String fName, String lName, double sal){
super(fName, lName);
salary = sal; }
public double getPay() {
return salary; }
public void printData() {
[Link]();
[Link]("Monthly salary: $" + salary);}
}
27
Inheritance…
Class Manager
firstName
lastName
is-a
Salary
printData
getPay
Class SalesManager
firstName
lastName
Salary
printData
getPay salesBonus
28
SalesManager Class
(Derived class from derived class)
class SalesManager extends Manager {
private double bonus; // Bonus Possible as commission.
// A SalesManager gets a constant salary of $1250.0
public SalesManager(String fName, String lName, double b) {
super(fName, lName, 1250.0);
bonus = b; }
public double getPay() {
return 1250.0; }
public void printData() {
[Link]();
[Link]("Bonus Pay: $" + bonus); }
}
29
public class PayRoll {
Main method
public static void main(String[] args) {
// Could get Data from tables in a Database.
Engineer fred = new Engineer("Fred", "Smith", 12.0, 8.0);
Manager ann = new Manager("Ann", "Brown", 1500.0);
SalesManager mary= new SalesManager("Mary", "Kate", 2000.0);
// Polymorphism, or late binding
Employee[] employees = new Employee[3];
employees[0]= fred;
employees[1]= ann; Java knows the
employees[2]= mary; object type and
for (int i=0; i < 3; i++) chooses the
employees[i].printData(); appropriate method
}
at run time 30
}
Output from main method
Fred Smith
Weekly pay: $96.0
Ann Brown
Monthly salary: $1500.0
Mary Barrett
Monthly salary: $1250.0
Bonus: $2000.0
Note that we could not write:
employees[i].getPay();
because getPay() is not a method of the superclass Employee.
In contrast, printData() is a method of Employee, so Java can find the
appropriate version.
31
Summary
• Software reuse reduces program-development time.
• The direct superclass of a subclass (specified by the keyword
extends in the first line of a class declaration) is the superclass
from which the subclass inherits.
• An indirect superclass of a subclass is two or more levels up
the class hierarchy from that subclass.
• In single inheritance, a class is derived from one direct
superclass.
• In multiple inheritance, a class is derived from more than one
direct superclass. Java does not support multiple inheritance..
• Every object of a subclass is also an object of that class’s
superclass.
• However, a superclass object is not an object of its class’s
subclasses. 32
Summary cont..
• An “is a” relationship represents inheritance. In an is a
relationship, an object of a subclass also can be treated as an
object of its superclass.
• A superclass’s public members are accessible wherever the
program has a reference to an object of that superclass or one of
its subclasses.
• A superclass’s private members are accessible only within the
declaration of that superclass.
• 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.
• When a subclass method overrides a superclass method, the
superclass method can be accessed from the subclass if the
superclass method name is preceded by the keyword super and a
dot (.) separator. (eg. [Link]() )
33
Summary cont..
• A subclass cannot access or inherit the private members of its
superclass.
• A superclass method can be overridden in a subclass to
declare an appropriate implementation for the subclass.
• The first task of any subclass constructor is to call its direct
superclass’s constructor, either explicitly or implicitly, to
ensure that the instance variables inherited from the
superclass are initialized properly.
• A subclass can explicitly invoke a constructor of its superclass
by using the superclass constructor call syntax. keyword
super, followed by a set of parentheses containing the
superclass constructor arguments. (eg super(44.54, 55) )
34
Exercise
• Write a Java program to demonstrate inheritance and method
overriding.
• Create a superclass called Student with:
Attributes: studentId, name, department, age, gpa,
• Methods: displayInfo() → prints all student details
isPassed() → returns true if GPA ≥ 2.0
updateGPA(double newGpa)
35
Create a subclass UndergraduateStudent that extends Student with:
• Attributes:
year
advisorName
creditHoursCompleted
• Methods:
showLevel()
addCredits(int credits)
isEligibleForGraduation() → credit ≥ 120
Create another subclass PostGraduateStudent with:
• Attributes:
researchTopic
supervisor
thesisProgress (0–100)
• Methods:
showResearch()
updateThesisProgress(int percent) 36
isThesisCompleted()
• Create one TestClass and in its main() method:
Create one object of each subclass.
Call all methods.
Print:
o
Whether undergraduate student is eligible for graduation
o
Whether postgraduate student completed thesis
o
Whether both students passed
37