Advanced
Programming CSE 201
Instructor: Sambuddho
(Semester: Monsoon 2025) Week 3 – Inheritance
Basics of Inheritance (in Java)
- Closely connected to polymorphism.
- Def_1: Referencing many related objects as one generic
type.
- Def_2: Reference of ‘parent’ class utilizing attributes and
methods of a ‘child’ class, depending on which one it is
referencing.
Slide Acknowledgement
CS15, Brown University
Basics of Inheritance (in Java)
- Closely connected to polymorphism.
- Def_1: Referencing many related objects as one generic
type.
- Def_2: Reference of ‘parent’ class utilizing attributes and
methods of a ‘child’ class, depending on which one it is
referencing.
Spot the Similarities
● What are the similarities between a convertible and a sedan?
● What are the differences?
5
Andries van Dam © 2016 9/27/16
Convertibles vs. Sedans
Convertible
Sedan
● Drive ● Turn off/on turn
● Brake engine
● Top Down Roof ● Play radio ● ● Fixed Roof
(Retractable Roof) Lock/unlock doors
6
Andries van Dam © 2016 9/27/16
Can we model this
in code? ● In some cases, Convertible
closely related to each other
objects can be very o
Convertibles and sedans drive the
o ● turnOnEngine()
same way Flip phones and
● turnOffEngine()
smartphones call the same way ● drive()
● Imagine we have an Convertible
and a Sedan class
o Sedan
Can we enumerate their similarities in
● parkInCompactSpace () ●
one place? turnOnEngine()
o ● turnOffEngine()
How do we portray their relationship
through code? ● drive()
Andries van Dam © 2016 9/27/16 Inheritance
● putTopDown()
● In OOP, inheritance is a way of
modeling very similar classes
● Inheritance models an “is-a”
o
relationship A sedan “is a” car Andries van Dam © 2016 9/27/16
o
A dog “is a” mammal
● Remember: Interfaces model an
“acts-as” relationship
● You’ve probably seen inheritance Animalia
o
before! Taxonomy from biology class
Chordata
Mammalia
…
8
Canis
Modeling Inheritance (1/2)
● This is an inheritance diagram
o
Each box represents a class
Mammal
Poodle Labrador
● A Poodle “is-a” Dog, a Dog “is-a”
Dog
Mammal
o
Transitively, a Poodle is a Mammal ●
“Inherits from” = “is-a”
o
Poodle inherits from Dog
o
Dog inherits from Mammal
● This relationship is not
bidirectional
o
A Poodle is a Dog, but not every Dog is a
Poodle (could be a Labrador, a German
Shepard, etc)
9
Andries van Dam © 2016 9/27/16
Modeling Inheritance (2/2)
●Superclass/parent/base: A class that is
inherited from
o
Poodle is the subclass
Mammal o
Dog is the superclass
●A class can be both a superclass and a
Dog o
subclass Ex. Dog
●In Java you can only inherit from one
superclass (no multiple inheritance)
o
Other languages, like C++, allow for multiple
Poodle Labrador
●Subclass/child/derived: A class that
inherits from another
●“A Poodle is a Dog”
10
Andries van Dam © 2016 9/27/16
inheritance, but too easy to mess up
Motivations for Inheritance
o
● A subclass inherits all of its parent’s public and protected capabilities If Car defines drive(),
Convertible inherits drive() from Car and drives the same way. This holds true for all of Convertible’s
subclasses as well
● Inheritance and Interfaces both legislate class’s behavior, although in very different ways
o
Interfaces allow the compiler to enforce method implementation
▪ An implementing class will have all capabilities outlined in an interface
o
Inheritance assures the compiler that all subclasses of a superclass will have the superclass’s public
capabilities without having to respecify code – methods are inherited
▪ A Convertible knows how to drive and drives the same way as Car because of inherited code ● Benefit of
inheritance
o
Code reuse
▪
If drive() is defined in Car, Convertible doesn’t need to redefine it! Code is ▪
inherited Only need to implement what is different, i.e. what makes Convertible
special
11
Andries van Dam © 2016 9/27/16
Superclasses vs Subclasses
● A superclass factors out commonalities among its subclasses
o
describes everything that all subclasses have in common.
NOTE: Java classes can have only one parent (super) class, unlike CPP.
● A subclass differentiates/specializes its superclass by:
o
adding new methods:
▪
oO
verriding inherited methods:
▪
12
Method Overriding
●
Override parent class ‘public’ methods (not private).
−
Child can access ‘public’ methods and attributes of parent class.
−
Using parent class attributes – super.<Attib_name>
−
Using parent class methods – super.f()
−
Calling parent class constructor
<subclass constructor>{
super(<arguments>)
}
Inheritance and Polymorphism
●
Polymorphism is an
incredibly powerful tool.
●
Allows for generic programming.
●
Treat multiple classes as their
generic type while still
allowing specific method
implementations to be executed.
●
Polymorphism+Inheritance is
strong generic coding
Inheritance and Polymorphism
15
Andries van Dam © 2016 9/27/16
Inheritance and Polymorphism
Inheritance and Polymorphism
17
Andries van Dam © 2016 9/27/16
Inheritance and Polymorphism
Why ?
Rules for Method Calls
●
1. Compiler looks at types of objects and method names, determines the appropaite
method based on the return type. The compiler also resolves.
●
2. Argument types.
●
3. Method types – ‘private’ , ‘static’ , ‘final’.
●
4. Polymorphic associations – dynamic binding at runtime.
Preventing Inheritance
●
1. What all a child class inherits:
●
Public objects and methods.
●
Private of parent is never inhreited.
●
Parent constructors (by default public, like everything else in Java).
●
Preventing inheritance:
●
You could also prevent specific methods
●
from being inherited without making them private.
Abstract Classes
Protected Access
●
‘Protected’ methods and objects cannot be accessed by objects of the class
much like ‘private’.
●
‘Protected’ methods and objects/variable can be accessed by child classes.
Object – the Cosmic Super Class
●
Object – parent of all classes (implicit); not of primitive types – int, char, byte etc.
●
Can be assigned to object of any class.
●
Arrays – regardless they are of primitive types or of classes, are of type Object.
Object – equals() method
●
Test if two objects ‘equal’ or same. Could mean many things – reference to
same object (default), same value etc.
●
Object class defines equal(). Other classes, can extend it with their own
definition.
Object – toString() method
●
Used to for printing a string equivalent information of the class. E.g. System.out.println(s); the
return type is String and the name is toString()
●
class MyClass{
●
...
●
public String toString(){
●
return “XYZ”;
●
}
●
}
Object Wrappers and Autoboxing
Object corresponding to a primitive type [Integer, Long, Flot, Double,Short, Byte
●
and Boolean].
Their objects are immutable – once a wrapper object has been created their values
●
cannot be changed.
They are ‘final’ and cannot be inherited.
●
Integer[] list;
●
list = new Integer[500];
●
list[0] = 1;
●
list[1] = 1;
●
list[i]++;
●
But list[i] == list[j] fails.
●
Object Wrappers and Autoboxing
●
list[i].intValue() == list[j].intValue();
Enum classes
●
Enumerated types – alternatives to constants. ● public enum Size {
SMALL, MEDIUM, LARGE, EXTRA_LARGE }
Generic ArrayLists
●
ArrayList is a generic class with a type parameter. ● An example of
polymorphism.
●
Provides a dynamically growing (or shrinking) array of objects.
●
ArrayList<Integer> mylist = new ArrayList<Integer>(); ●
or
●
ArrayList<Integer> mylist = new ArrayList<>();
Generic ArrayLists
●
Accessing ArrayList
elements
●
mylist.get(index);
●
mylist.set(index,val);
●
ArrayList.toString()
already defined. Prints
comma separated array
element values.
Interfaces
Interfaces
Interfaces – Single Inheritance with Multiple Interface
Implementations.
●
public interface Comparable{
●
public int compareTo(Object otherobject);
●
}
●
class Manager extends Employee implements Comparable { ● ....
●
}
Can be as many as the programmer
feels like.
Interfaces –Default Methods
●
Somewhat like a default constructor, but you cannot instantiate objects
of interfaces!
Popular Use Case – Callbacks.
●
Callback function frameworks use interfaces. ● Event listeners – need to
implement these interfaces and interface functions.
●
Timer t = new Timer(1000,new
TimePrinter());
Popular
Use Case – Callbacks.
Object Cloning
Object Cloning – Default:Shallow Copy
Object Cloning – Deep Copy: Implement
Clonable