Inheritance: Java Dr. Ashraf Uddin 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 27

Inheritance


The objectives of this presentation are:

 To explore the concept and implications of inheritance


 To define the syntax of inheritance in Java
 To understand the class hierarchy of Java
 To examine the effect of inheritance on constructors

Java Dr. Ashraf Uddin 1


Inheritance

The idea of inheritance is simple but powerful:

When you want to create a new class and there is


already a class that includes some of the code that
you want, you can derive your new class from the
existing class.

In doing this, you can reuse the fields and methods


of the existing class without having to write (and
debug!) them yourself.

Java Dr. Ashraf Uddin 2


Inheritance

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

Java Dr. Ashraf Uddin 3


Inheritance

A subclass inherits all the members (fields


and methods) from its superclass.

Constructors are not members, so they are


not inherited by subclasses, but the
constructor of the superclass can be invoked
from the subclass.

Java Dr. Ashraf Uddin 4


Inheritance

The Object class, defined in the java.lang


package, defines and implements behavior
common to all classes—including the ones
that you write.

In the Java platform, many classes derive


directly from Object, other classes derive
from some of those classes, and so on,
forming a hierarchy of classes.
Java Dr. Ashraf Uddin 5
Inheritance

All Classes in the


Java Platform are
Descendants of
Object.
At the top of the hierarchy, Object is the most general of all classes. Classes near
the bottom of the hierarchy provide more specialized behavior.
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Java Dr. Ashraf Uddin 6


Inheritance

Classes can be derived from classes that are


derived from classes that are derived from
classes, and so on, and ultimately derived
from the topmost class, Object. Such a class
is said to be descended from all the classes
in the inheritance chain stretching back to
Object.

Java Dr. Ashraf Uddin 7


Terminology

 The subclass inherits all of the public and protected


members of its parent.
 If the subclass is in the same package as its parent, it also
inherits the package-private members of the parent.

super class: Person


 The subclass can: - name: String
 Add new functionality - dob: Date
 Use inherited functionality
 Override inherited functionality

Employee
subclass: - employeeID: int
- salary: int
- startDate: Date

Java Dr. Ashraf Uddin 8


What You Can Do in a Subclass
 The inherited fields can be used directly, just like any
other fields.
 You can declare a field in the subclass with the same
name as the one in the superclass, thus hiding it (not
recommended).
 You can declare new fields in the subclass that are not in
the superclass.
 The inherited methods can be used directly as they are.
 You can write a new instance method in the subclass that
has the same signature as the one in the superclass, thus
overriding it.

Java Dr. Ashraf Uddin 9


What You Can Do in a Subclass
 You can write a new static method in the subclass that
has the same signature as the one in the superclass, thus
hiding it.
 You can declare new methods in the subclass that are not
in the superclass.
 You can write a subclass constructor that invokes the
constructor of the superclass, either implicitly or by
using the keyword super.

Java Dr. Ashraf Uddin 10


Private Members in a Superclass
 A subclass does not inherit the private members of its
parent class.

 However, if the superclass has public or protected


methods for accessing its private fields, these can also be
used by the subclass.

Java Dr. Ashraf Uddin 11


What really happens?

 When an object is created using new, the system must


allocate enough memory to hold all its instance variables.
 This includes any inherited instance variables

 In this example, we can say that an Employee "is a kind of"


Person.
 An Employee object inherits all of the attributes, methods and
associations of Person

Person Person
- name: String name = "John Smith"
- dob: Date dob = Jan 13, 1954
Employee
is a kind of name = "Sally Halls"
dob = Mar 15, 1968
Employee employeeID = 37518
- employeeID: int salary = 65000
- salary: int startDate = Dec 15, 2000
- startDate: Date
Java Dr. Ashraf Uddin 12
Inheritance in Java

 Inheritance is declared using the "extends" keyword

public class Person


Person
{
private String name;
- name: String
private Date dob;
- dob: Date
[...]

public class Employee extends Person


{ Employee
private int employeID; - employeeID: int
private int salary; - salary: int
private Date startDate; - startDate: Date
[...]

Employee anEmployee = new Employee();

Java Dr. Ashraf Uddin 13


Inheritance Hierarchy
 Each Java class has one (and only one) superclass.
 Inheritance creates a class hierarchy
 Classes higher in the hierarchy are more general and more abstract
 Classes lower in the hierarchy are more specific and concrete

Class

 There is no limit to the Class Class Class


number of subclasses a
class can have Class Class Class

 There is no limit to the depth


of the class tree.
Class

Java Dr. Ashraf Uddin 14


The class called Object

 At the very top of the inheritance tree is a class called


Object
 All Java classes inherit from Object.
 All objects have a common ancestor
 This is different from C++

 The Object class is defined in the java.lang package


 Examine it in the Java API Specification (https://
docs.oracle.com/javase/7/docs/api/java/lang/Object.html)

Java Dr. Ashraf Uddin 15


Constructors and Initialization

 Classes use constructors to initialize instance variables


 When a subclass object is created, its constructor is called.
 It is the responsibility of the subclass constructor to invoke the
appropriate superclass constructors so that the instance variables
defined in the superclass are properly initialized

 Superclass constructors can be called using the "super"


keyword in a manner similar to "this"
 It must be the first line of code in the constructor

 If a call to super is not made, the system will automatically


attempt to invoke the no-argument constructor of the
superclass.

Java Dr. Ashraf Uddin 16


Constructors - Example
public class BankAccount
{
private String ownersName;
private int accountNumber;
private float balance;

public BankAccount(int anAccountNumber, String aName)


{
accountNumber = anAccountNumber;
ownersName = aName;
}
[...]
}

public class OverdraftAccount extends BankAccount


{
private float overdraftLimit;

public OverdraftAccount(int anAccountNumber, String aName, float aLimit)


{
super(anAccountNumber, aName);
overdraftLimit = aLimit;
}
}
Java Dr. Ashraf Uddin 17
Inheritance

If a constructor does not explicitly invoke a


superclass constructor, the Java compiler
automatically inserts a call to the no-argument
constructor of the superclass.

If the super class does not have a no-argument


constructor, you will get a compile-time error.

Object does have such a constructor, so if Object


is the only superclass, there is no problem.
Java Dr. Ashraf Uddin 18
Inheritance

If a subclass constructor invokes a constructor of


its superclass, either explicitly or implicitly, you
might think that there will be a whole chain of
constructors called, all the way back to the
constructor of Object. In fact, this is the case.

It is called constructor chaining, and you need to


be aware of it when there is a long line of class
descent.

Java Dr. Ashraf Uddin 19


Method Overriding

 Subclasses inherit all methods from their superclass


 Sometimes, the implementation of the method in the superclass does
not provide the functionality required by the subclass.
 In these cases, the method must be overridden.

 To override a method, provide an implementation in the


subclass.
 The method in the subclass MUST have the exact same signature as
the method it is overriding.

Java Dr. Ashraf Uddin 20


Method overriding - Example
public class BankAccount
{
private String ownersName;
private int accountNumber;
protected float balance;

public void deposit(float anAmount)


{
if (anAmount>0.0)
balance = balance + anAmount;
}

public void withdraw(float anAmount)


{
if ((anAmount>0.0) && (balance>anAmount))
balance = balance - anAmount;
}

public float getBalance()


{
return balance;
}
Java } Dr. Ashraf Uddin 21
Method overriding - Example

public class OverdraftAccount extends BankAccount


{
private float limit;

public void withdraw(float anAmount) // Overriding method


{
if ((anAmount>0.0) && (getBalance()+limit>anAmount))
balance = balance - anAmount;
}

Java Dr. Ashraf Uddin 22


Object References and Inheritance

Inheritance defines "a kind of" relationship.


In the previous example, OverdraftAccount "is a kind of" BankAccount

Because of this relationship, programmers can "substitute"


object references.
A superclass reference can refer to an instance of the superclass
OR an instance of ANY class which inherits from the superclass.

BankAccount anAccount = new BankAccount(123456, "Craig");

BankAccount account1 = new OverdraftAccount(3323, "John", 1000.0);

BankAccount
anAccount name = "Craig"
accountNumber = 123456 OverdraftAccount
name = "John"
accountNumber =
account1 3323
limit = 1000.0
Java Dr. Ashraf Uddin 23
Dynamic Method Dispatch

 Dynamic Method Dispatch:


 It is the mechanism by which a call to an overridden

method is resolved at run time, rather than compile time.


 Through Dynamic Method Dispatch Java implements

 run-time polymorphism.

Java Dr. Ashraf Uddin 24


Final Methods and Final Classes

 Methods can be qualified with the final modifier


 Final methods cannot be overridden.
 This can be useful for security purposes.

public final boolean validatePassword(String username, String Password)


{
[...]

 Classes can be qualified with the final modifier


 The class cannot be extended
 This can be used to improve performance. Because there can be no
subclasses, there will be no polymorphic overhead at runtime.

public final class Color


{
[...]

Java Dr. Ashraf Uddin 25


The Object Classes
 There is a special class called Object, defined by java
 All other classes are subclasses of Object.
 So, Object is superclass of all other classes.
 Methods: 
 boolean equal (Object obj) 
          Indicates whether some other object is "equal to" this one.
 protected  void finalize()
          Called by the garbage collector on an object when garbage
collection determines that there are no more references to the
object.
   String toString()
 Returns a string representation of the object. The toString()
method return the description of the object. Also this method is
automatically called when an object is output using println().
Many class override the method and doing so allow them to
customize the description.
Java Dr. Ashraf Uddin 26
Review

What is inheritance? What is a superclass? What is a subclass?


Which class is at the top of the class hierarchy in Java?
What are the constructor issues surrounding inheritance?
What is method overriding?
What is a final method? What is a final class?

Java Dr. Ashraf Uddin 27

You might also like