Inheritance
Inheritance
A d a pt e d f r o m
w w w. c s . u t e p . e d u / v l a d i k / c s 24 01.10 a / C h _ 11 _ I n h e r i t a n c e _ Po l y m o r p h i
s m . p pt
1
Review: Classes
User-defined data types
◦ Defined using the “class” keyword
◦ Each class has associated
◦ Data members (any object type)
◦ Methods that operate on the data
New instances of the class are declared using the “new” keyword
“Static” members/methods have only one copy for a class, regardless of
how many instances are created
Example: Shared Functionality
public class Student { public class Professor {
String name; String name;
char gender; char gender;
Date birthday; Date birthday;
Vector<Grade> grades; Vector<Paper> papers;
Derived Class
C
Inheritance
Multiple inheritance:
◦ Subclass is derived from more than one superclass
◦ Not supported by Java
Not supported
Derived
Class
Inheritance (continued)
8
Inheritance
Why is this useful in programming?
◦ Allow us to specify relationships between types : “is-a” relationship
◦ Allows for code reuse: General functionality can be written once and
applied to any subclass. Subclasses can specialize by adding members
and methods, or overriding functions
class Box
public double area()
{ Note: Length and Width are
return 2 * (getLength() * getWidth() private data members of
Rectangle and hence cannot
+ getLength() * height be accessed directly in Box
+ getWidth() * height);
}
final Methods
Can declare a method of a class final using the keyword final
17
Calling methods of the superclass
◦ If subclass overrides public method of superclass, call to public
method of superclass is made as follows:
super.MethodName(parameter list)
18
class Box
public void setDimension(double l, double w, double h)
{
super.setDimension(l, w);
if (h >= 0)
height = h;
else
height = 0;
}
19
Defining Constructors of the Subclass
Call to constructor of superclass:
Must be first statement
Specified by super parameter list
in a class hierarchy, constructors are called in order of derivation,
from superclass to subclass
public Box() public Box(double l, double w,
double h)
{
{
super();
super(l, w);
height = 0;
height = h;
}
}
20
Assignment
Read about toString method
https://www.javatpoint.com/understanding-toString()-method
https://www.geeksforgeeks.org/object-tostring-method-in-java/
21