02 Inheritance
02 Inheritance
Programming II
Inheritance
Ford Mustang
Ford Model T
Mustang
Price: US$3590
Weight: 28 pounds
CPU: Intel 8088, 4.77MHz
RAM: 128K, 640K max
CMSC 330 Summer 2020 5
Object Oriented Programming
An Object-Oriented Language supports the following
fundamental concepts:
• Polymorphism
• Inheritance
• Encapsulation
• Abstraction
• Classes
• Objects
• Instance
• Method
10
CMSC 330 Summer 2020
Inheritance
Motivation: In real life objects have a hierarchical structure:
Shape
11
CMSC 330 Summer 2020
Inheritance
Define a general class
Later, define specialized classes based on
the general class
These specialized classes inherit properties
from the general class
Person
Student Employee
12
CMSC 330 Summer 2020
Inheritance
Person
Student Employee
14
CMSC 330 Summer 2020
is-a relationship
This inheritance relationship is known as an is-a
relationship
15
CMSC 330 Summer 2020
Why inheritance is useful
Enables you to define shared properties and
actions once
16
CMSC 330 Summer 2020
Person Class
public class Person {
private String name;
public Person(){
name = "";
}
public Person(String name){
this.name = name;
}
public void setName(String newName){
name = newName;
}
public String getName(){
Person
return name;
} -name
@Override
public String toString(){ +Person()
return "Name:"+name; +Person(String name):void
}
+setName(String name) : void
}
+getName() : String
17
CMSC 330 Summer 2020
Person
Student Class -name
+Person()
public class Student extends Person{ +Person(String name):void
private int id;
public Student() { +setName(String name) : void
id = 0; +getName() : String
}
public Student(String name, int id) {
super(name);
this.id = id;
} Student
public void setID(int idNumber) {
id = idNumber;
} -id
public int getID(){
return id;
}
+Student()
@Override +Student(String name, int id) : void
public String toString(){ +setID(int id) : void
return "Id:"+ id +"\tName:" + +getID(): int
getName();
}
+toString() : String
} 18
CMSC 330 Summer 2020
Dissecting the Student Class
• Extends: To specify that Student is a derived class (subclass) of Person
we add the descriptor “extends” to the class definition:
19
CMSC 330 Summer 2020
Super()
• super( ): When initializing a new Student object, we need to initialize its
base class (or superclass). This is done by calling super( … ). For
example, super( name) invokes the constructor Person( name)
• super( … ) must be the first statement of your constructor
• If you do not call super( ), Java will automatically invoke the base
class’s default constructor
20
CMSC 330 Summer 2020
Memory Layout and Initialization Order
• When you create a new derived class object:
• Java allocates space for both the base class instance variables and
the derived class variables
• Java initializes the base class variables first, and then initializes the
derived class variables
• Example:
Person ted = new Person( "Ted Goodman");
Student bob = new Student( "Bob Goodstudent", 100);
22
CMSC 330 Summer 2020
Inheritance
A Student “is a” Person:
23
CMSC 330 Summer 2020
Overriding Methods
• New Methods: A derived class can define entirely new
instance variables and new methods
• Overriding: A derived class can also redefine existing
methods
public class Person {
… The derived class can
redefine this method.
public String toString() { … }
}
public class Student extends Person {
…
public String toString() { … }
}
Student bob = new Student( "Bob Goodstudent", 100);
System.out.println("Bob's info: " + bob);
A. 0
B. garbage value
C. compiler error
D. runtime error
A. 0
B. garbage value
C. compiler error: variable not initialized.
D. runtime error
A. 0
B. garbage value
C. compiler error
D. runtime error
A. 0
B. garbage value
C. compiler error
D. runtime error: Null pointer exception
• This can be confusing to readers, since they may not have noticed
that you redefined name. Better to just pick a new variable name
32
CMSC 330 Summer 2020
Shadowing example
class Base {
public int x;
public Base(){x = 10;}
public String foo(){return x+"";}
}
• Why is this? After you have gone to all the work of setting up
privacy, it wouldn’t be fair to allow someone to simply extend your
class and now have access to all the private information
42
CMSC 330 Summer 2020
Quiz 5: True/False
A. True
B. False
A. True
B. False
49
CMSC 330 Summer 2020
Object
• Object is the superclass of all java classes
51
CMSC 330 Summer 2020
Polymorphism
• Java’s late binding makes it possible for a single reference variable to refer
to objects of many different types. Such a variable is said to be
polymorphic (meaning having many forms)
• Example: Create an array of various university people and print
Shape[ ] list = new Shape[3]; Output:
list[0] = new Rect(10,20);
list[1] = new Circle (10);
list[2] = new Triangle(3,4,5)
for (int i = 0; i < list.length; i++ )
System.out.println( list[i].getArea( ) );
• What type is list[i]? It can be a reference to any object that is derived from
Shape. The appropriate getArea will be called
52
CMSC 330 Summer 2020
getClass and instanceof
• Objects in Java can access their type information dynamically
• getClass( ): Returns a representation of the class of any object
• instanceof: You can determine whether one object is an instance of (e.g., derived
from) some class using instanceof. Note that it is an operator (!) in Java, not a
method call
53
CMSC 330 Summer 2020
Up-casting and Down-casting
• We have already seen that we can assign a derived class reference
anywhere that a base class is expected
Upcasting: Casting a reference to a base class (casting up the inheritance
tree). This is done automatically and is always safe
Downcasting: Casting a reference to a derived class. This may not be
legal (depending on the actual object type). You can force it by
performing an explicit cast
54
CMSC 330 Summer 2020
Safe Downcasting
• Can we check for the legality of a cast before trying it?
• A: Yes, using instanceof.
For(s:Shape){
if(s instanceof Circle){
Circle c = (Circle)s;
int r = c.getRadius();
}
}
55
CMSC 330 Summer 2020
Disabling Overriding with “final”
• Sometimes you do not want to allow method overriding
Correctness: Your method only makes sense when applied to the base
class. Redefining it for a derived class might break things
Efficiency: Late binding is less efficient than early binding. You know that
no subclass will redefine your method. You can force early binding by
disabling overriding
• We can disable overriding by declaring a method to be “final”
56
CMSC 330 Summer 2020
Disabling Overriding with “final”
• final: Has two meanings, depending on context:
57
CMSC 330 Summer 2020
Quiz 8
class Base {
final public void show() {
println("Base");
} A. Base
} B. Derived
class Derived extends Base { C. Compiler Error
public void show() { D. Runtime Error
println("Derived");
}
}
class Main {
public static void(String[] args){
Base b = new Derived();
b.show();
}
}
64
CMSC 330 Summer 2020
Inheritance versus Composition
• University parking lot permits: A parking permit object involves a university
Person and a lot name (“4”, “11”, “XX”, “Home Depot”)
Inheritance: Composition:
public class Permit extends Person { public class Permit {
String lotName; Person p;
String lotName;
// … // …
} }
• Which to use?
A parking permit “is a” person? Clearly no
A parking permit “has a” person? Yes, because a Person is one of the two
entities in a a permit object
So composition is the better design choice here
• Prefer Composition over inheritance
When in doubt or when multiple choices available, prefer composition over
Inheritance
65
CMSC 330 Summer 2020