0% found this document useful (0 votes)
21 views29 pages

Chapter 5-3 OOP Inheritance Part 3

Uploaded by

Wissem Smida
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)
21 views29 pages

Chapter 5-3 OOP Inheritance Part 3

Uploaded by

Wissem Smida
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/ 29

Inheritance

Objectives
To define the syntax of inheritance
in Java
To understand the class hierarchy of
Java
To understand the concept of
polymorphism
2
Terminology
Inheritance is a fundamental
Object Oriented concept

A class can be defined as a


"subclass" of another class.
Terminology
The subclass inherits superclass: Person
- name: String
all data attributes of its - dob: Date
superclass The subclass all associations of its
inherits all methods of its superclass
superclass

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

Override
Add new Use inherited
inherited
functionality functionality
functionality
What really happens?

When an • The system must allocate


object is enough memory to hold
all its instance variables.
created • This includes any
using inherited instance
new variables
Example
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
name = "Sally Halls"
is a kind of
dob = Mar 15, 1968
Employee employeeID = 37518
- employeeID: int salary = 65000
- salary: int startDate = Dec 15,
- startDate: Date 2000
Inheritance in Java
Inheritance is declared using the "extends" keyword
If inheritance is not defined, the class extends a class called Object

public class Person


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

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


Inheritance Hierarchy
Each Java class has one (and only one)
superclass. Class

Inheritance creates a class hierarchy


Class Class Class
Classes higher in the hierarchy are
more general and more abstract
Class Class Class
Classes lower in the hierarchy are
more specific and concrete
There is no limit to the number of
subclasses a class can have Class

There is no limit to the depth of the


class tree.
Constructors and Initialization
Classes use
When a subclass object is created, its
constructors
to initialize constructor is called.
instance
variables

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
7
Constructors and Initialization
Superclass constructors can be
called using the "super" keyword
in a manner similar to "this“
If a call to super is not made,
the system will automatically
It must be the first line of
attempt to invoke the no-
code in the constructor
argument constructor of the
superclass.
7
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;
}
}
8
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.
9
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;
}
}
10
Method overriding - Example
public class OverdraftAccount extends BankAccount {
private float limit;

public void withdraw(float anAmount) {


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

}
11
Object References and
Inheritance
Inheritance defines • In the previous example,
"a kind of" OverdraftAccount "is a kind of"
relationship. BankAccount

Because of this
• A superclass reference can refer to
relationship,
an instance of the superclass OR an
programmers can
instance of ANY class which inherits
"substitute"
from the superclass.
object references.
Object References and
Inheritance
BankAccount anAccount = new BankAccount(123456, "Craig");

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

BankAccount
anAccount name = "Craig"
accountNumber = 123456
OverdraftAccount
name = "John"
accountNumber = 3323
account1 12
limit = 1000.0
Polymorphism
In the previous slide, the two variables
are defined to have the same type at
compile time: BankAccount
The types of objects they are
referring to at runtime are
different
13
Polymorphism
WHAT HAPPENS WHEN THE
WITHDRAW METHOD IS INVOKED ON
EACH OBJECT?
anAccount refers
to an instance of
account1 refers to
an instance of
The method being
BankAccount OverdraftAccount. invoked on an object
is determined AT
withdraw method withdraw method RUNTIME and is
defined in
BankAccount is
defined in
OverdraftAccount based on the type of
invoked. is invoked.
the object receiving
the message.
13
Polymorphism
• means "many forms", and it occurs
when we have many classes that
Polymorphism
are related to each other by
inheritance.

Inheritance lets us • Polymorphism uses those methods


inherit attributes to perform different tasks. This
and methods from allows us to perform a single action
another class. in different ways.
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

The Object class is defined in the java.lang package


• The Object class is the cosmic super class does not inherit from any other
class has several important methods: toString, equals, hashCode, clone,
getClass

14
METHODS OF OBJECT CLASS
Method Description

Returns the Class class object of this object. The


public final Class getClass() Class class can further be used to get the metadata
of this class.

public int hashCode() Returns the hashcode number for this object.

public boolean equals(Object


Compares the given object to this object.
obj)
protected Object clone() throws Creates and returns the exact copy (clone) of this
CloneNotSupportedException object.

public String toString() Returns the string representation of this object.

Wakes up single thread, waiting on this object's


public final void notify() 15
monitor.
CONT..,
Method Description

Wakes up all the threads, waiting on this object's


public final void notifyAll()
monitor.
public final void wait(long Causes the current thread to wait for the specified
timeout)throws milliseconds, until another thread notifies (invokes
InterruptedException notify() or notifyAll() method).
Causes the current thread to wait for the specified
public final void wait(long
milliseconds and nanoseconds, until another
timeout,int nanos)throws
thread notifies (invokes notify() or notifyAll()
InterruptedException
method).
Causes the current thread to wait, until another
public final void wait()throws
thread notifies (invokes notify() or notifyAll()
InterruptedException
method).
protected void finalize()throws Is invoked by the garbage collector before object
Throwable is being garbage collected.
toString()
The toString
method Returns • Syntax: public String
the string
representation of toString()
the object.

if it is invoked this • The return string consist of


will return a string
which describes “@” and objects memory
the object. address in hexadecimal form.
17
EXAMPLE: TOSTRING();
class Student {
int rollno;
String name; Output:
String city; A@136bf0aa
A@136bf037
Student(int rollno, String name, String city) {
this.rollno = rollno;
this.name = name;
this.city = city;
}

public static void main(String args[]) {


Student s1 = new Student(101, "Raj", "lucknow");
Student s2 = new Student(102, "Vijay", "ghaziabad");

System.out.println(s1);// compiler writes here s1.toString()


System.out.println(s2);// compiler writes here s2.toString()
}

18
E X A M P L E TOSTRING ()
class Student {
int rollno;
String name;
String city;
Output:
Student(int rollno, String name, String city) {
this.rollno = rollno; 101 Jo hn L A
this.name = name; 101 Jo hn L A
this.city = city;
}

public String toString() {// overriding the toString() method


return rollno + " " + name + " " + city;
}

public static void main(String args[]) {


Student s1 = new Student(101, "John", "LA");
System.out.println(s1);
System.out.println(s1.toString());
}

19
THE EQUALS() METHOD

The default implementation


of the equals method in the
The equals() method
Object
compares the contents of
two objects. public boolean equals(Object obj) {
return (this == obj);
}

20
EXAPME OF THE EQUALS METHOD

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


BankAccount account2= new BankAccount(123456, "Craig");
If (account1.equals(account2)) different
System.out.println (“same account)
else
accounts
System.out.println (“different accounts”)

 Add this method to the class BankAccount


public boolean equals(Object o) {
if (o instanceof BankAccount) {
return accountNumber == ((BankAccount)o). accountNumber;
}
else
return false;
} 21
EXAPME OF THE EQUALS METHOD

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

BankAccount account2= new BankAccount(123456, "Craig"); Same


If (account1.equals(account2)) account
System.out.println (“same account)
else
System.out.println (“different accounts”)

22
Final Methods and Final
Classes
Methods can be qualified with the Classes can be qualified with the
final modifier final modifier
Final methods cannot be The class cannot be extended
overridden.
This can be useful for security
purposes.

public final boolean validatePassword(String public final class Color


username, String Password) {
{ [...]
[...]

23

You might also like