0% found this document useful (0 votes)
8 views89 pages

7_Inheritance_and_Interfaces

The document provides an overview of inheritance in Java, explaining concepts such as single, multilevel, and hierarchical inheritance, along with access specifiers and the use of the 'super' keyword. It also covers method overriding, dynamic method dispatch, and the implementation of interfaces for achieving multiple inheritance. Additionally, it discusses abstract classes and methods, final keywords, and provides examples and exercises for practical understanding.

Uploaded by

gohilsrushti64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views89 pages

7_Inheritance_and_Interfaces

The document provides an overview of inheritance in Java, explaining concepts such as single, multilevel, and hierarchical inheritance, along with access specifiers and the use of the 'super' keyword. It also covers method overriding, dynamic method dispatch, and the implementation of interfaces for achieving multiple inheritance. Additionally, it discusses abstract classes and methods, final keywords, and provides examples and exercises for practical understanding.

Uploaded by

gohilsrushti64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Inheritance

Mr. M.R.
Solanki
Sr. Lecturer, Information Technology,
manish_ratilal2002@yahoo.com
SBMP
Learning Outcomes

Students will be able to:


• Design and Develop Inheritance
related real world problems.
• Execute programs related to runtime
polymorphism.
• Use interface to achieve multiple
inheritance.
Inheritance
Inheritance Definition
 A class inherits qualities from its parent and it is
also having its own qualities.

 Using inheritance, we can create a general class


that defines traits (characteristics/attributes)
common to a set of related items.

 This class can then be inherited by other, more


specific classes, each adding those things that
are unique to it.

 In the terminology of Java, a class that is


inherited is called a superclass. The class that
does the inheriting is called a subclass.

# A subclass is a specialized version of a
superclass. It inherits all of the members
defined by the superclass and adds its
own, unique members.
Access Specifiers
 Java’s access modifiers are public, private, and
protected. Java also defines a default access
level.

 protected applies only when inheritance is


involved.

 When a member of a class is specified as public,


then that member can be accessed by any other
code.

Note: main( ) has always been preceded by the


public modifier because It is called by code that is
outside the program—by the Java run-time system.
Access Specifiers
 When a member of a class is specified as private,
then that member can only be accessed by other
default/public member methods of its class.

 When no access modifier is used, then by default


the member of a class is public within its own
package(directory), but cannot be accessed
outside of its package.
Single Level
Inheritance
Inheritance Basics
 To achieve Inheritance, we have to use extends
keyword
Inheritance Basics
Inheritance Output
Example

Consider class “Box” (we used in earlier chapters)


Another class “BoxWeight” inherits Box and having
unique properties i.e. weight.
Write an application to test the functionality
of given hierarchy of classes
Single Level Inheritance
Single Level Inheritance
Single Level Inheritance
Single Level Inheritance
Exercise

Define a class “Shape” having two data members


i.e. dim1 and dim2. Another class “Rectangle”
inherits Shape and having unique property i.e. area
which stores area of a rectangle.

Write an application to test the functionality


of given hierarchy of classes.
Member Access & Inheritance
Although a subclass includes all of the members of
its superclass, it cannot access private members of
superclass.
Member Access & Inheritance
private member access error
Need of super keyword
 The constructor for BoxWeight explicitly
initializes the width, height, and depth fields
which leads duplication of code in Box and
BoxWeight class.

 If super class declares its members as private


then subclass can not access it.

 Solution:
Whenever a subclass needs to refer to its
immediate superclass, it can use super keyword.

super has two general forms:


(i) To call the superclass’ constructor
(ii) To access super class member in case of name
duplication.
Constructors
 A subclass constructor can call a super class
constructor using super as follows:
super(arg-list);

Here, arg-list specifies any arguments needed by


the constructor in the superclass.

 super( ) must always be the first statement


executed inside a subclass’ constructor.
Constructors
improved version of the BoxWeight class:

class BoxWeight extends Box {


double weight;
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
}
To access Superclass Member
 Second use of super is to access the member of
super class in subclass.

super.member

Here, member can be either a method or an


instance variable.
To access Superclass Member
To access Superclass Member
To access Superclass Member
Hierarchical
Inheritance
Hierarchical Inheritance
 One class is being inherited by more than one
class. (a parent is having more than one child)
Hierarchical Inheritance
 Example/Exercise
Multilevel Inheritance
Multilevel Inheritance
 One class is being inherited by other class which
in turn is being inherited by another class.

 Grand Father -> Father -> Grandson hierarchy


Multilevel Inheritance
Example/ Exercise:

Consider the hierarchy of Box->BoxWeight


inheritance. A class Shipment is inheriting class
BoxWeight and having cost as a data member.
Write a Java application to test the
functionality of given classes.
Multilevel Inheritance
Calling Constructors:
Multilevel Inheritance
Calling Constructors:
Polymorphism
Method Overriding
 In a class hierarchy, when a method in a subclass
has the same name and type signature as a
method in its superclass, then the method in the
subclass is said to override the method in the
superclass.

 When an overridden method is called from


within its subclass, it will always refer to the
version of subclass. The version of the method
defined by the superclass will be hidden.
Method Overriding
Method Overriding

Output:
k: 3
Method Overriding
 If you wish to access the superclass version of
an overridden method, you can do it by super
Example: in this version of B, the superclass
version of show( ) is invoked within the subclass’
version

Output:
i and j: 1 2
k: 3

# Method overriding occurs only when the
names and the type signatures of the two
methods are identical. If they are not,
then the two methods are simply
overloaded.
Inheritance
Inheritance
A reference of a superclass can take a copy
of reference of an object of its subclass.(A
super class reference variable can refer a
subclass object)

Box b;

BoxWeight bw =new BoxWeight(2.0f, 3.5f, 4.5f,
10f);
b = bw;
b.volume();
# “
If a super class reference, refers a
subclass object it can access only those
qualities which a subclass has inherited.
# It can not access unique qualities of a sub
class.
Dynamic Method Dispatch

 Method overriding forms the basis for one of


Java’s most powerful concepts: dynamic method
dispatch

 Dynamic method dispatch is the mechanism by


which a call to an overridden method is resolved
at run time, rather than compile time

 Java uses “A super class reference variable can


refer a subclass object” principle to resolve
calls to overridden methods at run time
Dynamic Method Dispatch

 When an overridden method is called through a


superclass reference, Java determines which
version of that method to execute based upon
the type of the object being referred to at the
time the call occurs. Thus, this determination is
made at run time

 In other words, it is the type of the object being


referred to (not the type of the reference
variable) that determines which version of an
overridden method will be executed.
Dynamic Method Dispatch
 Example:
Dynamic Method Dispatch
Dynamic Method Dispatch
Applications of Runtime Polymorphism

 It allows a general class to specify methods that


will be common to all of its derivatives, while
allowing subclasses to define the specific
implementation of some or all of those methods.

 Overridden methods are another way that Java


implements the “one interface, multiple
methods” aspect of polymorphism.

 superclasses and subclasses form a hierarchy


which moves from lesser to greater
specialization.
Applications of Runtime Polymorphism

 Dynamic, run-time polymorphism mechanism


provides code reuse and robustness.

 The ability of existing code libraries to call


methods on instances of new classes without
recompilation them.
Applying Runtime Polymorphism
Applying Runtime Polymorphism
Applying Runtime Polymorphism
Applying Runtime Polymorphism
Applying Runtime Polymorphism
Abstract Method
 Sometimes a superclass declares the structure of
a given abstraction without providing a complete
implementation of every method (superclass only
defines a generalized form leaving details to be
filled by subclass)
 Such a class determines the nature of the
methods that the subclasses must implement.
 Java’s solution to this problem is the abstract
method
 Such methods are preceded with abstract
keyword as shown below:
abstract type
name(parameter-list);

 These methods are sometimes referred to as


subclasser responsibility because they have no
implementation specified in the superclass. Thus,
Abstract Class
 Any class that contains one or more abstract
methods must also be declared abstract.
 To declare a class abstract, you simply use the
abstract keyword in front of the class keyword at
the beginning of the class declaration.
 There can be no objects of an abstract class.
(cannot be directly instantiated with the new
operator)
 You cannot declare abstract constructors, or
abstract static methods.
 Any subclass of an abstract class must either
implement all of the abstract methods in the
superclass, or be declared abstract itself.
Abstract Example
Abstract Example
final keyword
final to prevent variable modification
 A field (variable) can be declared as final.
 Doing so prevents its contents from being
modified, making it, essentially, a constant.
 We can initialize it in two ways:
1. First, you can give it a value when it is
declared.
2.Assign it a value within a constructor.

Example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
final to prevent Overriding
 When you want to prevent method overriding
from occurring (to disallow a method from being
overridden), specify final as a modifier at the
start of its declaration.
 Methods declared as final cannot be overridden
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
final to prevent Inheritance
 To prevent a class from being inherited, precede
the class declaration with final
 Declaring a class as final implicitly declares all of
its methods as final, too
final class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A // Error
# “
It is illegal to declare a class as both
abstract and final since an abstract class
is incomplete by itself and relies upon its
subclasses to provide complete
implementations.
Does
Inheritance?

Java support Multiple
interface
Interface definition
 Using interface, you can specify what a class
must do, but not how it does it.

 Interfaces are syntactically similar to classes,


but they lack instance variables and their
methods are abstract (no body)
(When a class has all its member methods as
abstract that class becomes an interface)
Interface definition
 Once it is defined, any number of classes can
implement an interface

 Also, one class can implement any number of


interfaces (multiple inheritance)

 interface allows you to fully utilize the “one


interface, multiple methods” aspect of
polymorphism.
Defining an interface
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

interface Callback {
void callback(int param);
}
Implementing an Interface
 To implement an interface, include the
implements clause in a class definition, and then
create the methods required by the interface.
class classname [extends superclass] [implements
interface [,interface...]]
{
// class-body
}

Note: The methods that implement an interface must be


declared public. Also, the type signature of the
implementing method must match exactly the type
signature specified in the interface (method
overriding)
Implementing an Interface
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " +
p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement
interfaces " +
"may also define other members, too.");
}
}
Note: Classes that implement interface can
have their own methods as shown in the above
program.

# We can not create instances of an
interface.
# A reference of an interface can refer an
object of a class which implements that
interface.
# Variables declared inside an interface are
by default final.
Interface real world example
Interface real world example
Multiple Inheritance Exercise

Consider one interface Player having 3 methods i.e. start(),


stop() and play_pause(). Create class which implements this
interface and test the functionality of these methods.
Interface real world example

Consider an interface “StackIntf” having two member


methods push() and pop().

Create a class MyStack which implements StackIntf and


provides implementation logic of push() and pop() methods.

Write a Java program to demonstrate the functionality of


Stack using MyStack class.
Interface of mathematical constants
Multiple Inheritance

Consider a class Figure having dim1 and dim2 as instance


members and one abstract method area().
Class Rectangle inherits Figure and calculates area of the
rectangle.
Another class named “CenteredRectangle” is having x and y
as instance members (indicates center pixel) inherits
Rectangle class
and implements “DrawableShape” interface (having one
method draw() ). The draw() will display the center pixel of a
CentredRectangle object.

Write a Java program to display area and centered


pixel of a CentredRectangle object.
Multiple Inheritance
Multiple Inheritance
Multiple Inheritance Exercise

Consider a class named “Student” having id and name as


instance members. A class “Test” inherits Student and having
PT1 and PT2 as data members. There is one interface
named “Sports” which contains a variable points assigned
with value 5. (additional points of sports should be added in
total marks of student who participated and won in sports
activities in the semester)
Write a Java program to calculate the total marks of a
student.
Interfaces can be extended
 One interface can inherit another by use of the
keyword extends
interface A {
void meth1();
void meth2();
}
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
Interfaces can be extended
 One interface can inherit another by use of the
keyword extends
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}}
Discussion

Difference between a concrete class, an abstract class


and an interface. ?
Thanks!
Any questions?
You can find me at:
manish_ratilal2002@yahoo.com
Credits
 Java The Complete Reference, Ninth E
dition, Herbert Schildt
A ref_a;
B ref_b=new B();
ref_a=ref_b;

You might also like