Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
52 views

02 - Inheritance, Interface & Abstraction Class in Java

Inheritance in Java allows one class to acquire properties and behaviors of another class. This creates a parent-child relationship between the classes, where the child inherits characteristics of the parent. Inheritance promotes code reuse and is used to achieve runtime polymorphism through method overriding. The extends keyword indicates a class is inheriting from another parent class. A subclass inherits all non-private fields and methods from the parent class but can also define new fields and methods of its own while overriding existing parent class methods.

Uploaded by

Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

02 - Inheritance, Interface & Abstraction Class in Java

Inheritance in Java allows one class to acquire properties and behaviors of another class. This creates a parent-child relationship between the classes, where the child inherits characteristics of the parent. Inheritance promotes code reuse and is used to achieve runtime polymorphism through method overriding. The extends keyword indicates a class is inheriting from another parent class. A subclass inherits all non-private fields and methods from the parent class but can also define new fields and methods of its own while overriding existing parent class methods.

Uploaded by

Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Inheritance in Java

1) Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
2) The idea behind inheritance in java is that you can create new classes that are built
upon existing classes.
3) When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also. i.e. the subclass inherit the
MEMBERS of the Superclass. Here, Members=data members + methods.
4) Inheritance represents the IS-A relationship (Programmer is Employee), also known as
parent-child relationship.

Why use inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name

{ //methods and fields }

 The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
 In the terminology of Java, a class which is inherited is called parent or super class and
the new class is called child or subclass.

As displayed in the above figure, Programmer is the subclass and


Employee is the superclass. Relationship between two classes is
Programmer IS-A Employee. It means that Programmer is a type of
Employee.

In the side example, Programmer object can access the field of own
class as well as of Employee class i.e. code reusability.

Types of inheritance in java

 On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
 In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Note: Multiple inheritance is not supported in java
through class.

When a class extends multiple classes i.e. known as


multiple inheritance. For Example:

Single Inheritance Example Hierarchical Inheritance Example


Multilevel Inheritance Example

Q) Why multiple inheritance is not supported in java?

 To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
 Consider a scenario where A, B and C are three classes. The C class inherits A and B classes.
If A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
 Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error now.
Method Overriding in Java

 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
 In other words, if subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

 Method overriding is used to provide specific implementation of a method that is already


provided by its super class.
 Method overriding is used for runtime
polymorphism

Rules for Java Method Overriding

1. method must have same name as in the


parent class
2. Method must have same parameter as in
the parent class.
3. Must be IS-A relationship (inheritance).

Example of method overriding

In this example, we have defined the run method in


the subclass as defined in the parent class but it has
some specific implementation. The name and
parameter of the method is same and there is IS-A
relationship between the classes, so there is method
overriding.

Another E.g. for overriding


Super keyword

 The super keyword in java is a reference variable which is used to refer immediate
parent class object.
 Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) Super is used to refer immediate parent class instance 2) Super can be used to invoke parent class method
variable.

We can use super keyword to access the data member or field We can use super keyword to access the data member or
of parent class. It is used if parent class and child class have field of parent class. It is used if parent class and child class
same fields. have same fields.

In the above example, Animal and Dog both classes have a


common property color. If we print color property, it will print In the above example Animal and Dog both classes have eat()
the color of current class by default. To access the parent method if we call eat() method from Dog class, it will call the
property, we need to use super keyword. eat() method of Dog class by default because priority is given
to local.

To call the parent class method, we need to use super


keyword.
3) Super is used to invoke parent class constructor.

The super keyword can also be used to


invoke the parent class constructor. Let's
see a simple example:

Note: super() is added in each class


constructor automatically by compiler if
there is no super() or this().

As we know well that default constructor is


provided by compiler automatically if there is no constructor. But, it also adds super() as the
first statement.
1) With super(); constructor 2) Without super(); constructor

Super example: real use Let’s see the real use of super keyword. Here, Emp class inherits Person class
so all the properties of Person will be inherited to Emp by default. To initialize all the property, we are
using parent class constructor from child class. In such way, we are reusing the parent class constructor.
Upcasting

When reference variable of Parent class refers to the object of Child class, it
is known as upcasting. For example:

Note: Superclass reference variable can refer to Subclass Object (it’s nothing but polymorphism)

Note: you can only invoke methods that are either overridden or inherited from the superclass

TypeCasting
In right side e.g. Class A can’t access
printFromB() method of subclass then
typecasting is needed.
Syntax:
((subclass_name).object of Superclass)
Runtime and Compile time polymorphism

There are two types of polymorphism in java- Runtime polymorphism (Dynamic


polymorphism) and Compile time polymorphism (static polymorphism).
1) Runtime Polymorphism (or Dynamic polymorphism)

Method overriding is a perfect example of


runtime polymorphism. In this kind of
polymorphism, reference of class X can hold
object of class X or an object of any sub classes
of class X. For e.g. if class Y extends class X then
both of the following statements are valid:

Y obj = new Y();


//Parent class reference can be assigned to child
object
X obj = new Y();

Since in method overriding both the classes (base


class and child class) have same method, compile
doesn’t figure out which method to call at compile-
time. In this case JVM (java virtual machine)
decides which method to call at runtime that’s why
it is known as runtime or dynamic polymorphism.

2) Compile time Polymorphism (or Static


polymorphism)

Compile time polymorphism is nothing but the


method overloading in java. In simple terms we
can say that a class can have more than one
methods with same name but with different
number of arguments or different types of
arguments or both.

As you can see in the side example that the class


has three variance of methodA or we can say
methodA is polymorphic in nature since it is
having three different forms. In such scenario,
compiler is able to figure out the method call at
compile-time that’s the reason it is known as
compile time polymorphism.
Rule: Runtime polymorphism can't be achieved by data members.

Q) Do all instance variable of the superclass get inherited?

NO, if a member is private, it is NOT inherited.

Q) Can Super class access Subclass’s method?


For practice
NO.

Q) Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it
later.

Q) Why we cannot override static method?

Because static method is bound with class whereas instance method is bound with object. Static
belongs to class area and instance belongs to heap area.

Q) Can we override java main method?

No, because main is a static method

No. Method Overloading Method Overriding

Method overriding is used to provide the specific


Method overloading is used to increase the
1) implementation of the method that is already
readability of the program.
provided by its super class.

Method overriding occurs in two classes that


2) Method overloading is performed within class.
have IS-A (inheritance) relationship.

In case of method overloading, parameter must In case of method overriding, parameter must be
3)
be different. same.
Method overloading is the example of compile Method overriding is the example of run time
4)
time polymorphism. polymorphism.
In java, method overloading can't be performed
by changing return type (data type of method) of
Return type must be same or covariant in method
5) the method only. Return type can be same or
overriding.
different in method overloading. But you must
have to change the parameter.
Abstract class in Java
 Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
 Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
 Abstraction lets you focus on what the object does instead of how it does it.

When to use Abstract Methods & Abstract Class?

 Abstract methods are usually declared where two or more subclasses are expected to
do a similar thing in different ways through different implementations. These
subclasses extend the same Abstract class and provide different implementations for
the abstract methods.
 Abstract classes are used to define generic types of behaviors at the top of an object-
oriented programming class hierarchy, and use its subclasses to provide
implementation details of the abstract class.

Ways to achieve Abstraction: There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%) because it can also have concrete method(non-abstract method)
2. Interface (100%)

Abstract class in Java ()

1. whenever superclass is there only for to give you structure, also if we don’t want to
create object of that class make it abstract class
2. A class that is declared as abstract is known as abstract class.
3. It needs to be extended and its method implemented.
4. It cannot be instantiated (we can’t make object of abstract class).
5. An abstract class may also have concrete (non abstract) methods.
6. For design purpose, a class can be declared abstract even if it does not contain any
abstract methods

Consider the right side class hierarchy consisting of a Shape class which is inherited
by three classes Rectangle , Circle and Triangle. The Shape class is created to save
on common attributes and methods shared by the three classes Rectangle , Circle
and Triangle. calculateArea() is one such method shared by all 3 child classes and
present in Shape class.

Now, assume you write code to create objects for the classes depicted above. Let’s observe how these objects will look in a
practical world.

An object of the class rectangle, will gives a rectangle

An object of the class triangle, will gives a triangle

But what would an object of Class Shape look like in a practical world??

If you observe the Shape class serves in our goal of achieving inheritance and polymorphism. But it was not built to be
instantiated. Such classes can be labeled Abstract. An abstract class cannot be instantiated.

Note: It is possible that you DO NOT label Shape class as Abstract and then instantiate it. But such object will have no use in
your code and will open a room for potential errors. Hence this is not desirable.
Example abstract class: abstract class A{}

Abstract method

A method that is declared as abstract and does not have


implementation is known as abstract method.

Example abstract method: abstract void printStatus();//no


body and abstract

Example of abstract class that has abstract method

In this example, Bike is the abstract class that contains only


one abstract method run. It implementation is provided by In above e.g. there is no need of creation of the
the Honda class.
object of class Bike coz its implementation
provided in Honda class, therefore we made
class Bike as abstract class, as its just providing
abstraction of run method.

An abstract class can have data member, abstract method, method body, constructor
and even main() method.

Rule1: If there is any abstract method in a class, that class must be


abstract.

Rule2: If you are extending any abstract class that have abstract
method, you must either provide the implementation of the method or
make this class abstract.

Rule3: An abstract class may or may not have an abstract method. But
if any class has even a single abstract method, then it must be declared
abstract.
Final Keyword
The final keyword in java is used to restrict the user.

The java final keyword can be used in many context. Final can be:

1. variable
2. method
3. class

1) Java final variable

If you make any variable as final, you cannot change the value of final
variable (It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value


of this variable, but it can't be changed because final variable once
assigned a value can never be changed.

2) Java final method 3) Java final class

If you make any method as final, you cannot override If you make any class as final, you cannot
it. extend it.

Q) Is final method inherited? : Yes, final method is inherited but you cannot override it.

Note: every method in final class is always final method.


Q) What is blank or uninitialized final variable?

 A final variable that is not initialized at the time of declaration


is known as blank final variable.
 If you want to create a variable that is initialized at the time
of creating object and once initialized may not be changed,
it is useful. For example PAN CARD number of an
employee.
 It can be initialized only in constructor.

Q) Can we declare a constructor final?: No, because constructor is never inherited.


Interface
 An interface in java is a blueprint of a class (it’s something that object CAN DO).
 It has static constants and abstract methods.
 All methods in an interface are implicitly public and abstract
 The interface in java is a mechanism to achieve abstraction.
 The classes which implement the Interfaces must provide the method definition for all
the methods with public access (implemented methods should be defined with public access).
 The access specifiers used with classes are private, protected and public. While in
Interface only one specifier is used- Public
 There can be only abstract methods in the java interface not method body &
some constant variables (declared as final).
 It is used to achieve abstraction and multiple inheritance in Java.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class.

Why use Java interface? : -


There are mainly three reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

When do I have to use interfaces instead of abstract classes?

You should use interfaces when you want a full implementation of methods defined in
interfacess and use abstract classes when you want partial pieces for your design (for
reusability)
Cohesion & coupling

1) Cohesion: is used to indicate the degree to which


a class has a single, well-focused purpose.

 Low cohesion would mean that the class does


a great variety of actions and is not focused on
what it should do.
 High cohesion would then mean that the class
is focused on what it should be doing.

Benefits of Higher Cohesion:

 Highly cohesive classes are much easier to maintain and less frequently changed.
 Such classes are more usable than others as they are designed with a well-focused purpose.

2) Coupling:
 It refers to how related are two classes / modules and how dependent they are on each
other.
 Being low coupling would mean that changing something major in one class should
not affect the other.
 High coupling would make your code difficult to make changes as well as to maintain
it, as classes are coupled closely together, making a change could mean an entire
system revamp.
E.g. iPods are a good example of tight coupling: once the battery dies you might as well buy a new
iPod because the battery is soldered fixed and won’t come loose, thus making replacing very expensive.
A loosely coupled player would allow effortlessly changing the battery.

{All good software design will go for high cohesion and low coupling.}

Java 8 Interface Improvement: Since Java 8, interface can have default and static methods.
Internal addition by compiler
 The java compiler adds public and
abstract keywords before the
interface method. More, it adds
public, static and final keywords
before data members.
 In other words, Interface fields are
public, static and final by default,
and methods are public and
abstract.

Understanding relationship between classes and


interfaces

As shown in the figure side, a class extends


another class, an interface extends another
interface but a class implements an interface.
Java Interface Example: In this example, Printable
interface has only one method, its implementation is
provided in the A class.

Java Interface Example: Drawable

 In this example, Drawable interface has only one method.


 Its implementation is provided by Rectangle and Circle classes.
 In real scenario, interface is defined by someone but implementation is provided by
different implementation providers. And, it is used by someone else. The
implementation part is hidden by the user which uses the interface. Java Interface Example: Bank

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an


interface extends multiple interfaces i.e. known as
multiple inheritance.
Q) Multiple inheritance is not supported through
class in java but it is possible by interface, why?
As we have explained in the inheritance chapter,
multiple inheritance is not supported in case of class
because of ambiguity. But it is supported in case of
interface because there is no ambiguity as
implementation is provided by the implementation
class.
As you can see in the side example, Printable and
Showable interface have same methods but its
implementation is provided by class TestTnterface1,
so there is no ambiguity.

Interface inheritance Java 8 Default Method in Interface


A class implements interface but one interface extends
Since Java 8, we can have method body in interface. But we
another interface.
need to make it default method.

Java 8 Default Method in Interface

Since Java 8, we can have method body in interface. But


we need to make it default method. Let's see an example:

Java 8 Static Method in Interface Q) What is marker or tagged interface?

Since Java 8, we can have static method in interface. An interface that have no member is known as marker or
tagged interface. For example: Serializable, Cloneable,
Remote etc. They are used to provide some essential
information to the JVM so that JVM may perform some
useful operation.
Abstract class Interface
1) Abstract class can have abstract and non-abstract Interface can have only abstract methods. Since Java 8, it can
methods. have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-
Interface has only static and final variables.
static variables.
4) Abstract class can provide the implementation of
Interface can't provide the implementation of abstract class.
interface.
Example of abstract class and interface in Java: Let's see a simple example where we are
using interface and abstract class both.

Q) Can I define an abstract class


without adding an abstract method?

Of course.
Declaring a class abstract only
means that you don't allow it to
be instantiated on its own.
Declaring a method abstract
means that subclasses have to
provide an implementation for
that method.
The two are separate concepts,
but obviously you can't have an
abstract method in a non-abstract
class. You can even have abstract
classes with final methods but
never the other way around.

Nested Interface in Java

Note: An interface can have another interface i.e. known as nested interface. We will learn it
in detail in the nested classes chapter. For example:

You might also like