[Go to site: main page, start]

0% found this document useful (0 votes)
19 views38 pages

Topic 4 - Java Inheritance

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on key principles such as encapsulation, inheritance, polymorphism, and abstraction. It explains the relationships between classes, including 'has-a' and 'is-a' relationships, and details the inheritance hierarchy and the use of superclasses and subclasses. Additionally, it covers method overriding, the use of the super keyword, and dynamic method dispatch, highlighting the importance of these concepts in Java programming.

Uploaded by

Suresh Patnaik
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)
19 views38 pages

Topic 4 - Java Inheritance

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on key principles such as encapsulation, inheritance, polymorphism, and abstraction. It explains the relationships between classes, including 'has-a' and 'is-a' relationships, and details the inheritance hierarchy and the use of superclasses and subclasses. Additionally, it covers method overriding, the use of the super keyword, and dynamic method dispatch, highlighting the importance of these concepts in Java programming.

Uploaded by

Suresh Patnaik
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

Object-Oriented

Programming Using Java


Java Inheritance
Main Pillars of Object Oriented Programming
• Encapsulation
• Binding (or wrapping) code and data together into a single unit
• The terms “encapsulation” and “data-hiding” are used interchangeably
• The access specifiers can be used to control the level of encapsulation in Java
• Inheritance
• Code reuse: Specialization or "New code using old code"
• Ability that one object acquires properties and behaviors of another object
• Polymorphism
• Ability that one task is performed in different ways
• Ability for the same code to be used with different types of objects and behave differently
with each or "Old code using new code”
• Compile-time polymorphism (Overloading) vs Runtime polymorphism (Overriding) in Java
• Abstraction
• Hiding internal details and showing functionalities only
• In Java, abstraction is achieved by interfaces and abstract classes
Things and Relationships
• Object oriented programming leads to programs that are models
• Sometimes models of things in the real world
• Sometimes models of contrived or imaginary things
• There are many types of relationships between the things in the
models
• Chess piece has a position
• Chess piece has a color
• Chess piece moves (changes position)
• Chess piece is taken
• A rook is a type of chess piece
The “Has-A” Relationship
• Objects are often made up of many parts or have sub data.
• Chess piece: position, color
• Die: result, number of sides
• This “has-a” relationship is modeled by composition
• the instance variables or fields internal to objects
• Encapsulation captures this concept
The “Is-A” relationship
• Another type of relationship found in the real world
• A rook is a chess piece
• A queen is a chess piece
• A student is a person
• A faculty member is a person
• An undergraduate student is a student
• “is-a” usually denotes some form of specialization
• “is-a” is NOT the same as “has-a”!
Inheritance
• Inheritance: Forming new classes based on existing ones.
• A way to share/reuse code between two or more classes
• Another fundamental object-oriented technique
• Used to organize and create reusable classes

• Superclass: Parent class being extended


• Subclass: Child class that inherits behavior from
superclass
• Gets a copy of every field and method from superclass

• is-a relationship: Each object of the subclass also "is a(n)"


object of the superclass and can be treated as one.
Inheritance
• Inheritance: Forming new classes based on existing ones.
• A way to share/reuse code between two or more classes
• A fundamental object-oriented programming technique
• Used to organize and create reusable classes

• Superclass: Parent class being extended


• Subclass: Child class that inherits behavior from
superclass
• Gets a copy of every field and method from superclass

• is-a relationship: Each object of the subclass also "is a(n)"


object of the superclass and can be treated as one
Superclasses and Subclasses
• Object of one class is an object of another class
• Example: Rectangle is a quadrilateral.
• Class Rectangle inherits from class Quadrilateral
• Quadrilateral: superclass
• Rectangle: subclass
• Superclass typically represents larger set of objects than subclasses
• Example:
• Superclass: Vehicle
• Cars, trucks, boats, bicycles, …
• Subclass: Car
• Smaller, more-specific subset of vehicles
Java Inheritance: A Simple Example
class Vehicle {
protected String brand = "Ford";
public void honk() {
[Link]("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang";
public static void main(String[] args) {
Car myCar = new Car();
[Link]();
[Link]([Link] + " " + [Link]);
} Output:
} Tuut, tuut!
Ford Mustang
Nomenclature of Inheritance

• In Java, the extends keyword is used in the class header to specify


which preexisting class a new class is inheriting from
public class Student extends Person

• Person is said to be • Student is said to be


• The parent class of Student • A child class of Person
• The super class of Student • A sub class of Person
• The base class of Student • A derived class of Person
• An ancestor of Student • A descendant of Person
Superclasses and Subclasses: Examples
Results of Inheritance
public class A
public class B extends A
• The sub class inherits (gains) all instance variables and instance
methods of the super class, automatically
• Additional methods can be added to class B (specialization)
• The sub class can replace (redefine, override) methods from the
super class
Why Not Just Copy-and-Paste?
• Say I have an Employee class and want to create an
HourlyEmployee class that adds info about wages. Why not copy-
and-paste, then modify?

1. Fixing bugs: what if one were wrong?

2. Maintenance: what if Employee changes?

3. Code-reuse: would code that takes an Employee as a parameter also take


an HourlyEmployee?
Various Inheritance Types in OOP Paradigm
Superclasses and Subclasses: Inheritance hierarchy
• Inheritance hierarchy
• Inheritance relationships: tree-like hierarchy structure
• Each class becomes
• Superclass
• Supply data/behaviors to other classes
AND / OR
• Subclass
• Inherit data/behaviors from other classes

• A class extends EXACTLY one other class


• Extending two or more classes is MULTIPLE inheritance
• Java DOES NOT support multiple inheritance directly, rather it uses Interfaces!
Inheritance hierarchy: University Community Members

CommunityMember

Employee Student Alumnus

Faculty Staff

Administrator Teacher
Inheritance hierarchy: Geometrical Shapes

Shape

TwoDimensionalShape ThreeDimensionalShape

Circle Square Triangle Sphere Cube Tetrahedron


Inheritance in Java: In a Nutshell
• The keyword extends is used in Java for inheritance
• A class that extends another class is said to be a subclass. It is also known as a child
class or a derived class
• The class it extends is called a superclass. Sometimes the superclass is called a base
class or a parent class
• A subclass can also modify its method members. This is referred to as overriding
• A subclass inherits the non-private members of it’s superclass
• Syntax:
public class subclassName extends superclassName { … … … }
• Example:
public class Student extends Person {
… … …
}
Inheritance and Constructors
• Constructors DO NOT get inherited to a subclass
• Instead, the subclass’ constructor automatically calls it’s superclass’ zero-
parameter constructor before it executes any of the code in it’s own constructor
• If you do not want to use the parent’s zero-parameter constructor, you must
explicitly invoke one of the superclass’ other constructors with the keyword super
• If you do this, then the call to the superclass’ constructor must be the first line of
code in the subclass’ constructor
Student (String name) {
super (params);
… … …
}
• If the superclass has no zero-parameter constructor, the first line of any subclass
constructor MUST explicitly invoke another superclass constructor
Indirect Inheritance
• It is possible in Java to have an ARBITRARILY LONG line of ancestors
(i.e. many superclasses on your way to Object)
• The things we inherit from classes ABOVE the superclass are said to
be indirectly inherited.
• It does not matter where a class’ functionality comes from – a client
program always uses similar syntax to access the functionality
whether we
• define it in a class,
• inherit it directly from the superclass, or
• Inherit indirectly from another class in the class hierarchy
Constructor Calls in Class Hierarchy
class Alpha{
Alpha() {
[Link](“Inside Alpha’s Constructor“):
}
}
class Bravo extends Alpha{
Bravo() {
[Link](“Inside Bravo’s Constructor“):
}
}
class Charlie extends Bravo{
Charlie() {
[Link](“Inside Charlie’s Constructor“):
}
}
class CallingConstructorsDemo { Output:
public static void main(String[] args){ Inside Alpha's constructor
Charlie c = new Charlie(); Inside Bravo's constructor
} Inside Charlie's constructor
}
The protected Access Modifier
• protected access
• INTERMEDIATE level of protection between public and private
• the protected members accessible to
• Superclass members
• Subclass members
• Class members in the same package

• Subclasses access superclass member


• Keyword super and a dot (.)

22
Using protected Access Modifier
• Using protected instance variables
• Advantages:
• Subclasses can modify values directly
• Slight increase in performance
• Avoid set/get function call overhead
• Disadvantages:
• No validity checking
• Subclasses can assign illegal value!
• Implementation dependent
• Subclass methods more likely dependent on superclass implementation
• Superclass implementation changes may result in subclass modifications
• Fragile (brittle) software
Visibility modifiers for data and methods
Weakest private – only seen in class
access (UML -)
privileges
default (i.e. no access specifier mentioned explicitly) –
private access plus classes in the package
(UML none)

protected – default access plus subclasses anywhere


(UML #)
Strongest
access
public – protected access plus everything else
privileges
(UML +)
Overriding Methods
• Often a subclass does not want the exact method implementations as it’s
superclass
• In this case, the subclass can OVERRIDE the methods that it wants to change
• To override a method, we must re-declare the method in the subclass
• The new method must have the exact same signature as the superclass’ method
• Note: Only NON-PRIVATE methods can be overridden (private methods are
invisible to subclasses
• Note: we cannot override STATIC methods
• Note: we cannot override instance variables
• In the above two cases, when you attempt to override them, you are really hiding
them
• Method overriding occurs only when the names and the type signatures of the
two methods are IDENTICAL
• If not, two methods are simply OVERLOADED!
Method Overriding: Example
class Parent {
void show(){
[Link]("Parent's show()");
}
}
class Child extends Parent {
@Override
void show(){
[Link]("Child's show()");
}
}
class MethodOverrideDemo {
public static void main(String[] args){
Parent obj1 = new Parent();
[Link](); Output:
Parent obj2 = new Child(); Parent's show()
[Link](); Child's show()
}
}
Method Overriding or Method Overloading??
class Alpha { class OverrideOrOverloadDemo {
int i, j; public static void main(String[] args){
Alpha(int i, int j){ Bravo obj = new Bravo(1, 2, 3);
this.i = i; [Link]();
this.j = j; [Link](“This is k: “);
} }
void show(){ }
[Link](“i and j: “ + i + “ “ + j);
}
}
class Bravo extends Alpha {
int k;
Bravo(int i, int j, int k){
super(i, j);
this.k = k;
} Output:
void show(String msg){ i and j: 1 2
[Link](msg + k); This is k: 3
}
}
Method Overriding: Some Rules
• The access modifier for an overriding method can allow MORE, but not less,
access than the overridden method!
• Example: a protected instance method in the superclass can be made public, but not private,
in the subclass
• Final methods can not be overridden
• If we do not want a method to be overridden, we declare it as final
• Static methods can not be overridden
• Reason: Static method is bound with class whereas instance method is bound with an object
• When we define a static method with same signature as a static method in base class, it is
method hiding rather than method overriding!!
• Private methods can not be overridden
• The overriding method must have same return type (or subtype)
• We can call parent class method in overriding method using super keyword
• We CANNOT override constructors
The super Keyword
• The keyword super can be used in a subclass to refer to members of the
subclass’ superclass.
• Different Usage:
• super can be used to refer immediate parent class instance variable
• Acts somewhat like this, except that it always refers to the superclass of the subclass in which it is
used!
• Used to resolve the ambiguity caused to the JVM when a derived class and the base class have
data members having the same identifier name
• Super can be used to invoke immediate parent class method when derived class
overrides the same
• [Link]();
• [Link](params);
• super() can be used to invoke immediate parent class constructor (note: the keyword
new is not needed)
• super();
• super(params);
Instance Variable Ambiguity: Use of super
class Vehicle{
int maxSpeed = 120;
}

class Car extends Vehicle{


int maxSpeed = 180;
void display(){
[Link](“Car Maximum Speed: " + maxSpeed);
[Link](“Vehicle Maximum Speed: " + [Link]);
}
}

class TestVariableAmbiguityDemo {
public static void main(String[] args){
Car small = new Car();
[Link](); Output:
} Car Maximum Speed: 180
} Vehicle Maximum Speed: 120
Method Overriding: Use of super
class Parent {
void show(){
[Link]("Parent's show()");
}
}
class Child extends Parent {
@Override
void show(){
[Link]();
[Link]("Child's show()");
}
}
class SuperWithMethodDemo {
public static void main(String[] args){
Parent obj = new Child();
[Link](); Output:
} Parent's show()
} Child's show()
Use of super() with Constructors
class Person {
Person(){
[Link]("Person class Constructor");
}
}
class Student extends Person{
Student() {
super();
[Link]("Student class Constructor");
}
}
class SuperWithConstructorDemo{
public static void main(String[] args){
Student s = new Student(); Output:
} Person class Constructor
} Student class Constructor
Remarks on super() call in Constructors
• Call to super() must be first statement in Derived Class constructor
• If a constructor does not EXPLICITLY invoke a superclass constructor
• Java compiler automatically inserts a call to the zero-argument constructor of
the superclass
• If there is no zero-argument superclass constructor, there will be a compile-
time error!
• Eventually, a whole chain of constructors called, all the way back to the
constructor of Object!! -- Constructor Chaining !!
Dynamic Method Dispatch
• Polymorphism in Java is a concept by which we can perform a single action
in different ways
• There are two types of polymorphism in Java:
• Compile-time polymorphism  Method Overloading
• Runtime polymorphism  Method Overriding
• Real power of Method Overriding is in building a basis for runtime
polymorphism!
• Yields one of Java’s most powerful concepts: Dynamic Method Dispatch!
• A mechanism in Java by which a call to an overridden method is resolved at run time,
rather than at compile time!!
• The Principle behind Dynamic Method Dispatch:
• A superclass reference variable can refer to a subclass object!!!
• It is the type of the object being referred to (NOT the type of the reference variable)
that determines which version of an overridden method will be executed
Dynamic Method Dispatch: Illustration
class Alpha{ class DynamicMethodDispatchDemo {
void msg(){ public static void main(String args[]){
[Link]("Inside A’s msg method"); Alpha a = new Alpha();
} Bravo b = new Bravo();
} Charlie c = new Charlie();
class Bravo extends Alpha{ Alpha ref;
void msg(){
[Link]("Inside B’s msg method"); ref = a;
} [Link]();
} ref = b;
class Charlie extends Alpha{ [Link]();
void msg(){ ref = c;
[Link]("Inside C’s msg method"); [Link]();
} }
} }
Dynamic Method Dispatch: Illustration

• Output:
Inside A’s msg method a b Copy of A’s msg() method c
Inside B’s msg method
Inside C’s msg method
msg() msg()
If the type of reference
msg() msg() msg()
variable (ref) would
determine the call of the
method, we shall find the
execution of A’s copy of msg()
method in all three A Class Object B Class Object C Class Object
occasions!!!
Method Overload vs Method Override (Review)
Method Overloading Method Overriding
1. Helps to increase the 1. Used to grant the specific implementation of
readability of the program the method which is already provided by the
parent class
2. A compile-time polymorphism 2. A run-time polymorphism
3. Occurs within the class 3. Two classes having inheritance relationship
are involved
4. Return type may or may not be
the same 4. Return type must be the same or co-variant
5. Methods must have the same
name and different signatures 5. Methods must have the same name and same
signature
Keyword final Revisited
• Keyword final has three uses:
• to create the equivalent of a named constant (already discussed)
• To prevent overriding a method!
• To prevent inheriting a class!!
• final methods cannot be overridden
• A call to such methods may be resolved at compile time
• Java Compiler may use inline calls to small final methods by copying its
bytecode during compilation
• Essentially an early-binding for final methods
• Note: Java resolves calls to methods dynamically, at run time
• Late binding for normal method calls!
• Declaring a class as final IMPLICITLY declares all of its methods as final

You might also like