[go: up one dir, main page]

0% found this document useful (0 votes)
14 views65 pages

02 Inheritance

Uploaded by

Jamil Dk
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)
14 views65 pages

02 Inheritance

Uploaded by

Jamil Dk
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
You are on page 1/ 65

CMSC 132: Object-Oriented

Programming II

Inheritance

CMSC 330 Summer 2020 1


Mustang vs Model T

Ford Mustang

Ford Model T

CMSC 330 Summer 2020 2


Interior: Mustang vs Model T

CMSC 330 Summer 2020 3


Frame: Mustang vs Model T

Mustang

CMSC 330 Summer 2020


Model T 4
Compaq: old and new

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

CMSC 330 Summer 2020 6


Object
Objects have states and behaviors.
Example: A dog has states - color, name, breed
as well as behaviors – wagging the tail, barking,
eating.
An object is an instance of a class.
• If we consider the real-world, we can find many
objects around us, cars, dogs, humans, etc. All these
objects have a state and a behavior.

CMSC 330 Summer 2020 7


Class
A class can be defined as a template/blueprint
that describes the behavior/state that the object
of its type support.
public class Bicycle{
public int gear;
public int speed;
public Bicycle(int startSpeed, int startGear) {
gear = startGear;
speed = startSpeed;
}
public void setGear(int v){gear = v;}
public void applyBrake(int dec){speed -= dec;}
public void speedUp(int inc) { speed += inc; }
}
CMSC 330 Summer 2020 8
Java Class Example
Fraction Class
• Numerator
• Denominator
• Reduce a Fraction to Lowest Terms
• Addition, Multiplication
• …

• Now, let us implement the Fraction class.


• Code will be posted on course site.

CMSC 330 Summer 2020 9


Inheritance
• Classes can be derived from other classes, thereby
inheriting fields and methods from those classes.
• A class that is derived from another class is called a
subclass (also a derived class, extended class, or
child class).
• The class from which the subclass is derived is
called a superclass (also a base class or a parent
class).
• Derived (Child) class can be base (parent) class

10
CMSC 330 Summer 2020
Inheritance
Motivation: In real life objects have a hierarchical structure:

Shape

Circle Triangle Rectangle

Right -Triangle Equilateral - Square


Triangle

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

Undergrad Grad Faculty Staff

12
CMSC 330 Summer 2020
Inheritance
Person

Student Employee

Undergrad Grad Faculty Staff

Person: name, address, phone, email


Student: college, major, gpa
Employee: Salary, dateHired, office
Faculty: rank, officeHours
Staff: title
Undergrad: freshman,sophomore, junior, or senior)
Grad: advisor, level (ms or phd)
13
CMSC 330 Summer 2020
Inheritance cont.
What are some properties of a Person?
• name, height, weight, age

How about a Student?


• ID, major, gpa

Does a Student have a name, height, weight,


and age?
• Student inherits these properties from Person

14
CMSC 330 Summer 2020
is-a relationship
This inheritance relationship is known as an is-a
relationship

A Grad student is a Student


A Student is a Person.

Is a Person a Student? – Not necessarily!

15
CMSC 330 Summer 2020
Why inheritance is useful
Enables you to define shared properties and
actions once

Derived classes can perform the same actions


as base classes without having to redefine the
actions

If desired, the actions can be redefined –


method overriding

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:

public class Student extends Person {



}

• Notice that a Student class


• Inherits everything from the Person class
• A Student IS-A Person (wherever a Person is needed, we can use a
Student).

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

• What if the base class’s default constructor is undefined? Error


• You must use “super( … )”, not “Person( … )”.

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);

ted name Ted Goodman

name Bob Goodstudent


bob
id 100
21
CMSC 330 Summer 2020
Inheritance
• Inheritance: Since Student is derived from Person, a Student object
can invoke any of the Person methods, it inherits them

Student bob = new Student("Bob Goodstudent", 100);

String bobsName = bob.getName( ) );

bob.setName( "Robert Goodstudent" );

System.out.println( "Bob's new info: " +


bob.toString( ) );

22
CMSC 330 Summer 2020
Inheritance
A Student “is a” Person:

• By inheritance a Student object is also a Person object. We can


use a Student reference anywhere that a Person reference is
needed
Person robert = bob; // Okay: A Student is a Person

• We cannot reverse this. (A Person need not be a


Student.)

Student bob2 = robert; // Error! Cannot convert Person to Student

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);

Since bob is of type Student,


this invokes the Student toString( )
24
CMSC 330 Summer 2020
Overriding and Overloading
• Don’t confuse method overriding with method overloading.
Overriding: occurs when a derived class defines a method with the same
name and parameters as the base class.
Overloading: occurs when two or more methods have the same name, but
have different parameters (different signature).
Example: The base class defines
a method setName( )
public class Person {
public void setName(String n) { name = n; }

} Overriding: Same name and
public class Faculty extends Person { parameters; different
definition.
public void setName(String n) {
super.setName(“The Evil Professor ” + n);
}
public void setName(String first, String last) {
super.setName(first + “ ” + last);
} Overloading: Same name, but
} different parameters.
25
CMSC 330 Summer 2020
Quiz 1: Output of following program
class Test {
int i;
}
class Main {
public static void main(String args[]){
Test t;
System.out.println(t.i);
}
}

A. 0
B. garbage value
C. compiler error
D. runtime error

CMSC 330 Summer 2020 26


Quiz 1: Output of following program
class Test {
int i;
}
class Main {
public static void main(String args[]){
Test t;
System.out.println(t.i);
}
}

A. 0
B. garbage value
C. compiler error: variable not initialized.
D. runtime error

CMSC 330 Summer 2020 27


Quiz 2: Output of following program
class Test {
int i;
}
class Main {
public static void main(String args[]){
Test t = null;
System.out.println(t.i);
}
}

A. 0
B. garbage value
C. compiler error
D. runtime error

CMSC 330 Summer 2020 28


Quiz 2: Output of following program
class Test {
int i;
}
class Main {
public static void main(String args[]){
Test t = null;
System.out.println(t.i);
}
}

A. 0
B. garbage value
C. compiler error
D. runtime error: Null pointer exception

CMSC 330 Summer 2020 29


Quiz 3: Output of following program
class Base{
void display() {System.out.print(”Base ");}
}
class Child extends Base{
void display(){System.out.print(”Child ");}
}
Base b= new Base();
Child c = new Child ();
Base ref = b;
ref.display(); A. Compilation error
ref = c; B. Base Child
ref.display(); C. Child Base
D. Runtime error

CMSC 330 Summer 2020 30


Quiz 3: Output of following program
class Base{
void display() {System.out.print(”Base ");}
}
class Child extends Base{
void display(){System.out.print(”Child ");}
}
Base b= new Base();
Child c = new Child ();
Base ref = b;
ref.display(); A. Compilation error
ref = c; B. Base Child
ref.display();
C. Child Base
D. Runtime error

CMSC 330 Summer 2020 31


Overriding Variables: Shadowing
• We can override methods, can we override instance variables too?
• Answer: Yes, it is possible, but not recommended
• Overriding an instance variable is called shadowing, because it
makes the base instance variables of the base class inaccessible.
(We can still access it explicitly using super.varName).

public class Person { public class Staff


extends Person {
String name; String name;
// … // … name refers to
Staff’s name
} }

• 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+"";}
}

class Derived extends Base {


public int x;
public Derived(){ x = 20;}
public String foo(){return (x + "\t" + super.x);}
}

Derived d = new Derived();


d.foo();

CMSC 330 Summer 2020 33


Shadowing example
class Base {
public int x;
public Base(){x = 10;}
public String foo(){return x+"";}
}

class Derived extends Base {


public int x;
public Derived(){ x = 20;}
public String foo(){return (x + "\t" + super.x);}
}

Derived d = new Derived();


d.foo();
20 10
CMSC 330 Summer 2020 34
Shadowing example
class Base {
public int x;
public Base(){x = 10;}
public void foo(){return x);}
}

class Derived extends Base {


public int x;
public Derived(){ x = 20;}
public void foo(){return (x + “\t” + super.x);}
}
Derived d = new Derived();
Base b = d;
d.x;
b.x;
CMSC 330 Summer 2020 35
Shadowing example
class Base {
public int x;
public Base(){x = 10;}
public String foo(){return x);}
}

class Derived extends Base {


public int x;
public Derived(){ x = 20;}
public String foo(){return (x + “\t” + super.x);}
}
Derived d = new Derived();
Base b = d;
d.x; 20
b.x; 10
CMSC 330 Summer 2020 36
super and this
• super: refers to the base class object
• We can invoke any base class constructor using super( … ).
• We can access data and methods in the base class (Person)
through super. E.g., toString( ) and equals( ) invoke the
corresponding methods from the Person base class, using
super.toString( ) and super.equals( ).

• this: refers to the current object


• We can refer to our own data and methods using “this.” but this
usually is not needed
• We can invoke any of our own constructors using this( … ). As
with the super constructor, this can only be done within a
constructor, and must be the first statement of the constructor.
Example:
public Fraction(int n) {
this(n,1);
}
37
CMSC 330 Summer 2020
Memory Layout
class Base{
private int a;
protected int b;
protected int c;
protected void m1(){} Base
public void m2(){}
}

class Child extends Base{ Child


private int d;
public void m1(){}
public void m3(){}
}
The Java Virtual Machine does not mandate any particular internal
structure for objects.

CMSC 330 Summer 2020 38


Memory Layout
VTABLE Base object
class Base{
private int a; Pointer to m1() Pointer to
vtable
protected int b; Pointer to m2()
protected int c; a
protected void m1(){} b
public void m2(){} c
}

class Child extends Base{


private int d;
public void m1(){}
public void m3(){}
}

CMSC 330 Summer 2020 39


Memory Layout
VTABLE Base object
class Base{
private int a; Pointer to m1() Pointer to
vtable
protected int b; Pointer to m2()
protected int c; a
protected void m1(){ } b
public void m2(){ } c
}

class Child extends Base{ Child object


private int d; VTABLE Pointer to
public void m1(){ } vtable
public void m3(){ } Pointer to m1() a
} Pointer to m2() b
Pointer to m3() c
d
CMSC 330 Summer 2020 40
Memory Layout
VTABLE Base object
class Base{
private int a; Pointer to m1() Pointer to
vtable
protected int b; Pointer to m2()
protected int c; a
protected void m1(){} b
public void m2(){} c
}

class Child extends Base{ Child object


private int d; VTABLE Pointer to
public void m1(){} vtable
public void m3(){} Pointer to m1() a
} Pointer to m2() b
Each class has one vtable. Pointer to m3() c
d
All objects of the this class shares the vtable.
CMSC 330 Summer 2020 41
Inheritance and Private
• Private members:
• Child class inherits all the private data of Base class
• However, private members of the base class cannot be
accessed directly

• 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

Except Object, which has no superclass, every class has


one and only one direct superclass.

A. True
B. False

CMSC 330 Summer 2020 43


Quiz5: True/False

Except Object, which has no superclass, every class has


one and only one direct superclass.

A. True
B. False

CMSC 330 Summer 2020 44


Quiz 6:
class Base {
public void foo(){
println("Base"); A. Base
B. Derived
}
C. Compiler Error
} D. Runtime Error
class Derived extends Base {
private void foo(){
println("Derived");
}
}

Base b = new Derived();
b.foo();

CMSC 330 Summer 2020 45
Quiz 6:
class Base {
public void foo(){
println("Base"); A. Base
B. Derived
}
C. Compiler Error
} D. Runtime Error
class Derived extends Base {
private void foo(){ It is compiler error to give
println("Derived"); more restrictive access to a
derived class function which
}
overrides a base class
} function.

Base b = new Derived();
b.foo();

CMSC 330 Summer 2020 46
Quiz 7:
class Animal has a subclass Mammal. Which of
the following is true:

A. Because of single inheritance, Mammal can have no


subclasses.
B. Because of single inheritance, Mammal can have no other
parent than Animal.
C. Because of single inheritance, Animal can have only one
subclass.
D. Because of single inheritance, Mammal can have no siblings.

CMSC 330 Summer 2020 47


Quiz 7:
class Animal has a subclass Mammal. Which of
the following is true:

A. Because of single inheritance, Mammal can have no


subclasses.
B. Because of single inheritance, Mammal can have no other
parent than Animal.
C. Because of single inheritance, Animal can have only one
subclass.
D. Because of single inheritance, Mammal can have no siblings.

CMSC 330 Summer 2020 48


Access level

Modifier Class Package Subclass World


public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

49
CMSC 330 Summer 2020
Object
• Object is the superclass of all java classes

• The class Object has no instance variables, but defines


a number of methods. These include:
toString( ): returns a String representation of this
object
equals(Object o): test for equality with another
object o

• Every class you define should, overrides these two


methods with something that makes sense for your
class (hashCode method is also included in the group)
50
CMSC 330 Summer 2020
Early and Late Binding
• Motivation: Consider the following example:
Base b = new Child();
b.toString();

• Q: Should this call Base’s toString or Child’s toString?


• A: There are good arguments for either choice:
Early (static) binding: The variable b is declared to be of type Base.
Therefore, we should call the Base’s toString
Late (dynamic) binding: The object to which b refers was created as a
“new Child”. Therefore, we should call the Child’s toString
Pros and cons: Early binding is more efficient, since the decision can be
made at compile time. Late binding provides more flexibility
• Java uses late binding (by default): so Faculty toString is called
(Note: C++ uses early binding by default.)

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

Person bob = new Person( … );


Person ted = new Student( … );

if ( bob.getClass( ) == ted.getClass( ) ) // false (ted


is really a Student)

• 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

• Illegal downcasting results in a ClassCastException run-time error

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();
}
}

Only Circle has getRadius method

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:

• Define symbolic constants:


public static final int MAX_BUFFER_SIZE = 1000;

• Indicate that a method cannot be overridden by derived classes


public class Parent { Subclasses cannot
… override this method
public final void someMethod( ) { … }
}
Illegal! someMethod is
public class Child extends Parent { final in base class.

public void someMethod( ) { … }
}

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();
}
}

CMSC 330 Summer 2020 58


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");
}
}

Final methods cannot be



Base b = new Derived();
overridden. Compiler
b.show();
Error: overridden method
… is final

CMSC 330 Summer 2020 59


Quiz 9
class Base {
public static void show() {
println("Base”);
A. Base
} B. Derived
} C. Compiler Error
class Derived extends Base {
public static void show() {
println("Derived");
}
}

Base b = new Derived();;
b.show();

CMSC 330 Summer 2020 60
Quiz 9
class Base {
public static void show() {
println("Base”);
A. Base
} B. Derived
} C. Compiler Error
class Derived extends Base {
public static void show() {
when a function is static,
println("Derived");
runtime polymorphism
} doesn't happen.
}

Base b = new Derived();;
b.show();

CMSC 330 Summer 2020 61
Abstract Class
Abstract classes cannot be instantiated, but
they can be subclassed.
It may or may not include abstract methods.
public abstract class Shape {
private String id;
public Shape (String id) {this.id = id};
public abstract double getArea();
public String getId() {return id;}
}

This abstract method must be defined in a


concrete subclass.

CMSC 330 Summer 2020 62


Abstract Class
public abstract class Shape {
private String id;
public Shape (String id) {this.id = id};
public abstract double getArea();
public String getId() {return id;}
}

public class Circle extends Shape {


private double radius;
public Circle (double r) { Must implement
super(“Circle”); radius = r;
}
double getArea(){return Math.PI * radius * radius;}
public double getRadius() {return radius;}
public void setRadius(double r) {radius = r}
}
CMSC 330 Summer 2020 63
Inheritance versus Composition
• Inheritance is but one way to create a complex class from
another. The other way is to explicitly have an instance
variable of the given object type. This is called composition
Common Object:
Derive a new Add ObjA as an
public class ObjA {
class from instance variable.
public methodA( ) { … }
ObjA.
}
Inheritance: Composition:
public class ObjB extends ObjA { public class
ObjB {
… ObjA a;
// call methodA( ); // call a.methodA( )
} }

• When should I use inheritance vs. Composition?


• ObjB “is a” ObjA: in this case use inheritance
• ObjB “has a” ObjA: in this case use composition

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

You might also like