7_Inheritance_and_Interfaces
7_Inheritance_and_Interfaces
Mr. M.R.
Solanki
Sr. Lecturer, Information Technology,
manish_ratilal2002@yahoo.com
SBMP
Learning Outcomes
Solution:
Whenever a subclass needs to refer to its
immediate superclass, it can use super keyword.
super.member
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
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.
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
}