You are on page 1of 17

Java

Inheritance
Inheritance
Same inheritance concept of C++ in Java with some
modica8ons
In Java,
One class inherits the other using extends keyword
The classes involved in inheritance are known as
superclass and subclass
Mul3level inheritance but no mul3ple inheritance
There is a special way to call the superclasss constructor
There is automa8c dynamic method dispatch

2
Simple Inheritance

3
Prac8cal Example

4
Superclass variable reference to
Subclass object

5
Using super

6
Using super

7
Using super

8
Mul8level Inheritance

Inside X's constructor


Inside Y's constructor
Inside Z's constructor

9
Method Overriding

10
Dynamic Method Dispatch

11
Abstract Class
abstract class A
contains abstract method abstract method f()
No instance can be created of an abstract class
The subclass must implement the abstract method
Otherwise the subclass will be a abstract class too

12
Abstract Class

13
Using nal with Inheritance

To prevent overriding

To prevent inheritance

14
Object Class
There is one special class, Object, dened by Java
All other classes are subclasses of Object
That is, Object is a superclass of all other classes
This means that a reference variable of type Object
can refer to an object of any other class
Also, since arrays are implemented as classes, a
variable of type Object can also refer to any array

15
Objects toString()
The toString( ) method returns a string that contains
a descrip8on of the object on which it is called
Also, this method is automa8cally called when an
object is output using println()
Many classes override this method
Doing so allows them to tailor a descrip8on
specically for the types of objects that they create

16
Objects toString()

17

You might also like