3.2 Inheritance

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Inheritance

Application Programming: Java Programming


Contents

• Defining Inheritance
• Relationships of Inheritance
• Rules of Inheritance
• super and this references
• super() and this() methods
• Constructor Chaining
• Casting

2
Objectives
• Define inheritance
• Identify relationships of inheritance
• Describe the rules of inheritance
• Describe the difference between this and
super references
• Describe the difference between this() and
super() methods
• Describe how to create constructors
• Describe the steps in constructor chaining
• Describe how to convert data types using casting

3
Defining Inheritance
• Inheritance is the ability to derive new classes from
existing ones. A derived class ("subclass") inherits the
instance variables and methods of the base class
("superclass"), and may add new instance variables and
methods.
• Inheritance defines a hierarchical relationship among
classes wherein one class shares the attributes and
methods defined in one or more classes.
• Inheritance is a relationship among classes in which one
class shares the structure and behavior of another. A
subclass inherits from a superclass.

4
Relationships of Inheritance
• “is-a” relationship
• a subclass can be used wherever a superclass can be used
• implemented in Java by extending a class
• “has-a” relationship
• a whole-class relationship between a class and its parts
• also known as composition or aggregation
• implemented in Java by instantiating an object inside a class

“is-a” relationship “has-a” relationship

Vehicle Car

Engine
Wheel
Car Bus
5
Rules of Inheritance

• A class can only inherit from one class (known as single inheritance).
• A subclass is guaranteed to do everything the superclass can do.
• A subclass inherits members from its superclass and can modify or
add to its behavior and properties.
• A subclass can define members of the same name in the superclass,
thus hiding the superclass members.
• Inheritance is transitive (i.e., class A inherits from class B, including
what B inherited from class C).
• All classes inherit from the Object class - the highest in the
inheritance hierarchy.
• private members, hidden members, and constructors are not
inherited by subclasses.

6
Inheritance Hierarchy

Object

System Math Vehicle Person

Car Boat Employee Doctor

7
Implementing Inheritance
• Inheritance is implemented in Java by the extends keyword
class Student extends Person { class Person {
String course; // set variables to private
private static int maleCount;
double grade;
private static int femaleCount;
private String name;
/* private char sex;
* other members of Person class private int age;
* can be accessed here
/*
*/
* setters & getters, set to public
} */
public static void main(String[] args) { public int getAge() { return age;}
Student junior = new Student(); public void setAge(int a) { age = a;}
public String getName() { return name;}
public void setName(String n) { name = n;}
// access current class members
public char getSex() { return sex;}
junior.course = "Computer Science"; public void setSex(char s) { sex = s;}
junior.grade = 1.5; /*
* other methods here
// access superclass members */
}
junior.setName("Andrew");
junior.setAge(21);
junior.setSex('M');
}

8
this and super
• this is a reference to the object of the current class
• It can be used to distinguish instance variables from local
variables
• It can be assigned to other references, or passed as a
parameter, or cast to other types
• It cannot be used in a static context
• super is a reference to the object of a superclass
• Used to access hidden members of the superclass
• It cannot be assigned to other references, nor passed as a
parameter, nor cast to other types
• It cannot be used in a static context

9
Using this and super

class Student extends Person { class Person {


private String course; // set variables to private
private static int maleCount;
private double grade;
private static int femaleCount;
static int studentCount; private String name;
private char sex;
// setters & getters private int age;
public String getCourse(){return course;}
/*
public void setCourse(String course) {
* setters & getters, set to public
this.course = course; */
} public int getAge() { return age;}
public double getGrade(){return grade;} public void setAge(int a) { age = a;}
public void setGrade(double grade) { public String getName() { return name;}
public void setName(String n) { name = n;}
this.grade = grade;
public char getSex() { return sex;}
} public void setSex(char s) { sex = s;}
// access superclass members /*
public void printInfo() { * other methods here
System.out.println(super.getName()); */
}
System.out.println(super.getSex());
System.out.println(super.getAge());
}
}

10
Constructor Chaining
• Constructor chaining is invoking all the constructors in the
inheritance hierarchy.
• Constructor chaining guarantees that all superclass
constructors are called.
• Constructors are invoked starting with the current class up
to the Object class, then they are executed in reverse
order.

11
this() and super()
• this(<optional parameters>)
• used to call constructors within the same class
• used to implement local chaining of constructors
• must be the first statement in a constructor and can only be
used in a constructor
• super(<optional parameters>)
• used to invoke constructors in the immediate superclass
• used to implement chaining of subclass-to-superclass
constructors
• must be the first statement in a constructor and can only be
used in a constructor

12
Implementing Constructor Chaining
class Person {
private String name;
private char sex;
private int age;
Person() { // default constructor
sex = 'M'; age = 0;
}
}
class Student extends Person {
String course;
double grade;
static int studentCount;
Student() { // default constructor
super(); // chain to superclass
studentCount++;
}
Student(String n) { // overloaded constructor (non-default)
this(); // local chain
super.setName(n);
}
}
public static void main(String[] args) {
Student junior = new Student("Andrew");
}
13
Casting
• Casting is converting from one data type to another
• Implicit casting is an implied casting operation
• Explicit casting is a required casting operation
• Primitive casting is converting a primitive data type to another
data type
• Widening conversion is casting a narrower data type to a broader
data type
• Narrowing conversion is casting a broader data type to a narrower
data type
• Reference casting is converting a reference data type to another
• Upcasting is conversion up the inheritance hierarchy
• Downcasting is conversion down the inheritance hierarchy
• Casting between primitive and reference type is not allowed
• In Java, casting is implemented using () operator

14
Reference Casting Flow
“Upcasting” “Downcasting”
Vehicle

Car Boat Plane

Imagine it as a container!

Vehicle

Car Boat Plane

15
Reference Casting Rule

Operation Conversion Type


string concatenation implicit upcasting
parameter passing implicit upcasting (if formal parameter
is a superclass)
(all others) explicit casting (downcasting or
upcasting )

16
Implementing Reference Casting
public class Vehicle {}
public class Car extends Vehicle {}
public class Boat extends Vehicle {}
public class Plane extends Vehicle {}

public static void main(String args[]) {


Vehicle v = new Vehicle();
Car c = new Car();
Boat b = new Boat();
Plane p = new Plane();
Vehicle vc = new Car();

v = c; // This will compile.


c = v; // This will not compile!!!
b = p; // will this compile?
b = (Boat) v; // will this compile?
c = (Car) vc; // will this compile?
}

17
Key Points
• Inheritance is deriving a new class (subclass) from an existing class
(superclass)
• Inheritance can exhibit an “is-a” or “has-a” relationship
• In Java, a class can only inherit from a single class
• All classes inherit from Object class – the highest in the inheritance
hierarchy
• In Java, inheritance is implemented by the extends keyword
• this is a reference to the object of the current class
• super is a reference to the object of a superclass
• this() is used to call constructors within the same class
• super() is used to invoke constructors in the immediate superclass
• Casting is converting from one data type to another

18
Questions and Comments

19

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy