0% found this document useful (0 votes)
47 views

Lecture 06 Inheritance

The document discusses inheritance and object-oriented programming concepts including: 1. It introduces inheritance and how it allows new classes to reuse and extend existing classes. 2. It covers syntax for creating inheritance relationships, member access and inheritance, constructors in inheritance, and multi-level hierarchies. 3. It provides examples of inheritance applied to modeling posts in a social network application, including defining a superclass Post and subclasses MessagePost and PhotoPost that extend Post.

Uploaded by

Umer Beshir
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Lecture 06 Inheritance

The document discusses inheritance and object-oriented programming concepts including: 1. It introduces inheritance and how it allows new classes to reuse and extend existing classes. 2. It covers syntax for creating inheritance relationships, member access and inheritance, constructors in inheritance, and multi-level hierarchies. 3. It provides examples of inheritance applied to modeling posts in a social network application, including defining a superclass Post and subclasses MessagePost and PhotoPost that extend Post.

Uploaded by

Umer Beshir
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Lecture 06

Chapter 4

Inheritance
By: Mequanent Argaw
Debre Markos University

12/7/2015 Department of ECE, College of Technology 1


Topic Outline
 Introduction to Inheritance

 Syntax to create Inheritance relationships

 Member Access and Inheritance

 Constructors in Inheritance

 Multi level Hierarchy

 Super-class references and Sub-class Objects

 Method Overriding

 Advantages of Inheritance
12/7/2015 Department of ECE, College of Technology 2
Introduction to Inheritance
Inheritance is one of the primary capabilities of OOP.

Inheritance is a form of software reuse in which a new class is created by

absorbing an existing class’s members and embellishing them with new or

modified capabilities.

The idea of inheritance is that you can create new classes that are built on

existing classes.

When you inherit from an existing class, you reuse ( or inherit) its methods

and fields and you add new methods and fields to adapt to your new class

to new situations.

12/7/2015 Department of ECE, College of Technology 3


Basics :Understanding Inheritance
 When you design with inheritance, you put
common code in a class and then tell other
more specific classes that the common ( more
abstract) class is their class is their superclass.
 The subclass inherits from the superclass.
 In Java we say the subclass extends the
superclass
 The subclass inherits member fields and
member methods defined inside the superclass.
12/7/2015 Department of ECE, College of Technology 4
Case Study: A Network Application
 In this example we try to analyze a small part of a social-network application

like Facebook or Google+.

 The part we will be concentrating on is the News Feed feature.

 The News Feed is the list of messages that should appear on screen when a

user opens the application’s main page.

 Initially, we will only have two types of posts appearing in our news feeds:

 Text posts which we call messages, and

 Photo posts consisting of a photo and a caption

 In this application we will prototype the engine that stores and displays these

messages.
12/7/2015 Department of ECE, College of Technology 5
The Network’s Application : Classes
 Some of the classes needed to implement the application are easily
identified.
 We must have a class MessagePost to represent message posts and a
class PhotoPost to represent photo posts.

Department of ECE, College of


12/7/2015 6
Technology
Discussion of the Application’s Classes
Schema
 Even though the application is not yet complete, we have defined the core of
the application the data and methods that store and operate on the essential
information.
 Before we move ahead and design the rest let us discuss the possible
challenges we will face.
 The fundamental and most obvious problem is code duplication.

 Annoyingly we have to write everything twice.

 Problems of maintaining duplicate code ( changes have to be done twice).

 There is a danger of introducing errors ( we might forget to add changes).

 What about if we introduced an additional class say an Activity Post class ?

 We essentially write a third version of the same class schema and


consequently a similar source code.
12/7/2015 Department of ECE, College of Technology 7
Solution: Inheritance
 The idea is simple:

 instead of defining the MessagePost and PhotoPost classes completely

independently, we first define a class that contains everything these two

have in common.

 We shall call this class Post.

 Then we can declare that a MessagePost is a Post, and

 A PhotoPost is a Post

 Finally, we add the extra details needed for a message post to the MessagePost

class, and those for a photo post to the PhotoPost class.

 Essentially we described the common features only once.

12/7/2015 Department of ECE, College of Technology 8


Network Application: Using Inheritance

 Inheritance allows us to define one class as an extension of another.

 MessagePost inherits from class Post.


 PhotoPost inherits from Post.

 Using Java’s syntax:


 class MessagePost extends Post

 class PhotoPost extends Post


 class Post is called Superclass or parent class.

 MessagePost and PhotoPost are called child

classes or Subclasses.

12/7/2015 Department of ECE, College of Technology 9


Member Access and Inheritance
 Access Modifiers:

 public : a class’s public members are accessible everywhere in a program.

 private: a class’s private members are accessible only within the

class itself.

 So what happens in inheritance

 public members are inherited.

 private members are not inherited.

 Do we have an other level of access control ?

 Yes : protected
12/7/2015 Department of ECE, College of Technology 10
Protected Members
 Using the access modifier protected offers an intermediate level of

access between public and private.

 A class’s protected members can be accessed by members of that

class, and by all classes defined inside the same package.

 A superclass’s protected members can be accessed by:


 Members of that superclass;

 Members of its subclasses, and

 Members of other classes in the same package.

 protected members have up to package level access.

12/7/2015 Department of ECE, College of Technology 11


Member Access and Inheritance cont…
 All public and protected superclass members retain their original

access modifier when they become members of the subclass.

 A superclass’s private members are not accessible outside the class

itself. Rather they are hidden in its subclass and can be accessed only

through the public or protected methods inherited from the

superclass.

 Methods of a subclass cannot directly access private members of their

superclass.

 A subclass can change the state of private superclass instance variables


12/7/2015 Department of ECE, College of Technology 12
only through non-private methods provided in the superclass.
POP QUIZ

1. When creating a subclass, what keyword is


used to include a superclass?

2. Does a subclass include the members of its


superclass?

3. Does a subclass have access to the private


members of its superclass?
12/7/2015 Department of ECE, College of Technology 13
Constructors and Inheritance
 It is possible for both superclasses and subclasses to have their own

constructor.

 Question: What constructor is responsible for building an object of

the subclass?

 Answer: The constructor for the superclass constructs the superclass

portion of the object, and the constructor for the subclass constructs

the subclass part.

 REASON: this is because the superclass has no knowledge of or

access to any element in the subclass.


12/7/2015 Department of ECE, College of Technology 14
Constructors and Inheritance cont…

 When only the subclass defines a


constructor the process is straight forward:
 Simply construct the subclass object.

 The superclass portion of the object is


constructed automatically using its default
constructor.

12/7/2015 Department of ECE, College of Technology 15


Constructors and Inheritance cont…
 When both the superclass and the subclass define constructors,
the process is a bit more complicated because both the
superclass and subclass constructors must be executed.

 In this case you must use Java’s keyword, super, which has two
general forms:

 Use super to call a superclass constructor

 Secondly use super to access a member of the superclass that


has been hidden by a member of a subclass.

12/7/2015 Department of ECE, College of Technology 16


1. Using super to call Superclass
Constructors
 A subclass can call a constructor defined by its superclass by the use of the
following form of super:
 super(parameter-list)

 Here, parameter-list specifies any parameters needed by the constructor in the


superclass.
 super(parameter-list) must always be the first statement executed inside a
subclass constructor.
 Any form of constructor defined by the superclass can be called by super().

 The constructor executed by the super call will be the one that matches the
arguments if more than one constructor is defined in the superclass.

12/7/2015 Department of ECE, College of Technology 17


POP QUIZ

1. How does a subclass execute its superclass’


constructor?

2. Can parameters be passed via super() ?

3. Can super() go anywhere within a subclass’


constructor?

12/7/2015 Department of ECE, College of Technology 18


2. Using super to Access Superclass
Members
 The second form of super acts similarly to the keyword this.

 super is used, in this case, to always refer to the superclass of the

subclass in which it is used.

 The syntax is as follows:


 super.member

 This form of super is most applicable to situations in which

member names of a subclass hide members by the same name in

the superclass.
12/7/2015 Department of ECE, College of Technology 19
Multi level Hierarchy
Besides using simple class hierarchies that consist of only a superclass

and a subclass, you can also create hierarchies that contain multiple

inheritance layers.

It is perfectly legal to use a subclass as a superclass of another.

Example: given three classes A, B and C, C can be a subclass of B which

is in turn a subclass of A.

In multilevel hierarchies each subclass inherits all of the traits found

in all of its superclasses.

12/7/2015 Department of ECE, College of Technology 20


Example: TwoDShape multiple inheritance layer

// Define superclass Shape


public class Shape {
// Private member variable
private String color;
// Constructor
public Shape (String color) { this.color = color; }
@Override
public String toString() {
return "Shape of color=\"" + color + "\""; }
// All shapes must has a method called getArea()
public double getArea() {
System.err.println("Shape unknown! Cannot compute area!");
return 0; // Need a return to compile the program }
}
12/7/2015 Department of ECE, College of Technology 21
Cont …
// Define Triangle, subclass of Shape
public class Triangle extends Shape {
// Private member variables
private int base;
private int height;
// Constructor
public Triangle(String color, int base, int height) {
super(color);
this.base = base;
this.height = height;
}
@Override
public String toString() {
return "Triangle of base=" + base + " and height=" + height + ", subclass of " + super.toString(); }
@Override
public double getArea() { return 0.5*base*height; }
}

12/7/2015 Department of ECE, College of Technology 22


Cont …
class RightAngle extends Triangle{
private String type;
RightAngle(String t, String c, int b, int h){
super(c, b, h);
type = t;
}
@Override
public String toString() {
return type + “ ” + super.toString(); }
@Override
public double getArea() {
return super.getArea();
}
}
12/7/2015 Department of ECE, College of Technology 23
Testing Inheritance Hierarchy

12/7/2015 Department of ECE, College of Technology 24


Points to Understand
Class RightTriangle makes use of previously defined classes of

Triangle and TwoDShape, adding only the extra information it needs

for its own, specific application.

This is the value of inheritance: it allows the reuse of code.

 super() always refers to the constructor that is closes to the

superclass.

In a class hierarchy, if a superclass constructor requires parameters,

then all subclasses must pass those parameters “up the line.”

12/7/2015 Department of ECE, College of Technology 25


When are Constructors called ?
Question : When a subclass object is created, whose constructor is executed

first ?
A) The one in the subclass

B) The one defined by the superclass

Answer:
 In a class hierarchy, constructors are called in order of derivation, from superclass to

subclass.

 Even if you use super(), since it is always executed first, the order is still from superclass

to subclass. If super() is not used, then the default( parameterless) constructor of each

superclass will be executed.

12/7/2015 Department of ECE, College of Technology 26


Cont…
If you think about it, it is reasonable that constructors are

executed in order of derivation.


 Because a superclass has no knowledge of any of its subclasses.

 Any initialization it needs to perform is separate from and

possibly prerequisite to any initialization performed by the

subclass,

 Therefore, it must be executed first.

12/7/2015 Department of ECE, College of Technology 27


Subtyping: Superclass References and Subclass Objects

Since Java is a strongly typed language, we know that type compatibility is

strictly enforced.

Therefore, a reference variable for one class type cannot normally refer to

an object of another class type.

In general, an object reference variable can refer only to objects of its type.

Exception occurs in Subtyping: a reference variable of a superclass can

be assigned to any subclass derived from that superclass.

The type defined by a subclass definition is a subtype of the type of its

superclass
12/7/2015 Department of ECE, College of Technology 28
Subtyping Example
class X{ class SupSubRef{
int a; public static void main(String [] args){
public X(int i){ X x1 = new X(10);
a = i; X x2;
} Y y1 = new Y(5, 6);
x2 = x1;
} System.out.println(“x2.a: ” + x2.a);
class Y extends X{ x2 = y1;
int b; System.out.println(“x2.a: ” + x2.a);
public Y(int i, int j){ x2.a = 19;
super(j); x2.b = 27; // impossible
b = i; }
} }
}

12/7/2015 Department of ECE, College of Technology 29


Subtyping cont…
It is important to understand that it is the type of the reference

variable – not the type of the object that it refers to – that determines

what members can be accessed.

When a reference to a subclass object is assigned to a superclass type

reference variable, you will have access only to those parts of the

object defined by the superclass.

This makes sense because the superclass has no knowledge of what a

subclass adds to it.

12/7/2015 Department of ECE, College of Technology 30


POP QUIZ
1. Can a subclass be used as a superclass for
another subclass?

2. In a class hierarchy, in what order are the


constructors called?

3. Given that Jet extends Airplane, can an


Airplane reference refer to a Jet object?
12/7/2015 Department of ECE, College of Technology 31
Method Overriding
In a class hierarchy, when a method in a subclass has the same
 Return type and

 Method signature then

the method in the subclass is said to override the method in the

superclass.

When an overridden method is called within a subclass, it will always

refer to the version of the method defined by the subclass. The

version of the method defined by the superclass will be hidden.

12/7/2015 Department of ECE, College of Technology 32


Method Overriding Cont…
Method overriding occurs only when the return types and signatures of the two

methods are identical. If not, then the two methods are simply overloaded.

Method overriding forms the basis for one of Java’s most powerful concepts:

dynamic method dispatch.

Dynamic method dispatch is the mechanism by which a call to an overridden

method is resolved at run time rather than compile time.

Dynamic method dispatch is important because this is how Java implements

run time Polymorphism.

12/7/2015 Department of ECE, College of Technology 33


Difference between Static binding and Dynamic binding

 Static binding in Java occurs during compile time while


dynamic binding occurs during runtime. Static binding
uses type(Class) information for binding while dynamic
binding uses instance of class(Object) to resolve calling
of method at run-time. Overloaded methods are bonded
using static binding while overridden methods are
bonded using dynamic binding at runtime.

12/7/2015 Department of ECE, College of Technology 34


Differences between method overloading and method overriding

No. Method Overloading Method Overriding

Used to increase the readability of Used to provide the specific


1) the program. implementation of the method that is
already provided by its super class.

2) Performed within class. Occurs in two classes that have IS-A


(inheritance) relationship.
3) Parameter must be different. Parameter must be same.

4) Method overloading is the example Method overriding is the example of


of compile time polymorphism. run time polymorphism.
Can't be performed by changing
return type of the method only. Return type must be same or covariant
5) Return type can be same or different in method overriding.
in method overloading. But you
must have to change the parameter.

12/7/2015 Department of ECE, College of Technology 35


Example
Java Method Overloading example

class OverloadingExample{  
static int add(int a,int b){return a+b;}  
static int add(int a,int b,int c){
return a+b+c;
}  
}  
Java Method Overriding example

class Animal{  
void eat(){
System.out.println("eating...");
}  
}  
class Dog extends Animal{  
void eat(){
System.out.println("eating bread...");
}  
}
12/7/2015 Department of ECE, College of Technology 36
Advantages of Inheritance
Avoiding code duplication: the use of inheritance avoids the need to write

identical or very similar copies of code twice

Code reuse : existing code can be reused. If a class similar to the one we

need already exists, we can derive the new class from the existing class and

reuse some of the existing code instead of writing everything from scratch.

Easier maintenance: A change to a field or a method that is shared between

different types of subclasses need to be made only once.

Extendibility : Using inheritance, it becomes much easier to extend an

existing application in certain ways.

12/7/2015 Department of ECE, College of Technology 37

You might also like