0% found this document useful (0 votes)
7 views

Inheritance

Java Inheritance topic

Uploaded by

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

Inheritance

Java Inheritance topic

Uploaded by

Chaitra M Bhat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter 8:

Inheritance
Chapter Topics
Chapter 6 discusses the following main topics:
⚫ Inheritance Basics
⚫ Using Super
⚫ Method Overriding
⚫ Dynamic Method Dispatch
⚫ Abstract Methods
⚫ Final
Class Hierarchy

•Good class design puts all common features as high in


the hierarchy as reasonable
•The class hierarchy determines how methods are
executed
•inheritance is transitive
What is Inheritance?
Generalization vs. Specialization
•Real-life objects are typically specialized versions of
other more general objects.
•The term “insect” describes a very general type of
creature with numerous characteristics.
•Grasshoppers and bumblebees are insects
•They share the general characteristics of an insect.
•However, they have special characteristics of their own.
•grasshoppers have a jumping ability, and
•bumblebees have a stinger.
•Grasshoppers and bumblebees are specialized
versions of an insect.
Inheritance

Insect
Contains those attributes
and methods that are
shared by all insects.

BumbleBee Grasshopper

Contains those attributes and Contains those attributes and


methods that specific to a methods that are specific to a
Bumble Bee. Grasshopper.
The “is a” Relationship

•The relationship between a superclass and an


inherited class is called an “is a” relationship.
•A grasshopper “is a” insect.
•A poodle “is a” dog.
•A car “is a” vehicle.
•A specialized object has:
•all of the characteristics of the general object, plus
•additional characteristics that make it special.
•In object-oriented programming, inheritance is used
to create an “is a” relationship among classes.
The “is a” Relationship

•We can extend the capabilities of a class.


•Inheritance involves a superclass and a subclass.
•The superclass is the general class and
•the subclass is the specialized class.
•The subclass is based on, or extended from, the superclass.
•Super classes are also called base classes, and
•Sub classes are also called derived classes.
•The relationship of classes can be thought of as parent classes
and child classes.

11-7
Inheritance

•The subclass inherits fields and methods from the


superclass without any of them being rewritten.
•New fields and methods may be added to the
subclass.
•The Java keyword, extends, is used on the class
header to define the subclass.
public class B extends A
Types of Inheritance
•Single Inheritance

• Multiple Inheritance (Through Interface)


•Multilevel Inheritance •Hierarchical Inheritance

•Hybrid Inheritance
Example:
class A class B extends A
{ {
int i; int j;
void showi() void showj()
{
{
System.out.println(“j: " + j);
System.out.println("i: " + i); }
} void sum()
} {
System.out.println("i+j: " + (i+j));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
A a = new A();
B b = new B();
a.i = 10;
System.out.println("Contents of a: ");
a.showi();
b.i = 7;
b.j = 8;
System.out.println("Contents of b: ");
b.showi();
b.showj();
System.out.println("Sum of I and j in b:");
b.sum();
}
}
Super
• ‘super’ is a keyword used to refer to instance
variables of super class from sub class.
✔ super.a=10;
• It is used to call a constructor of super class from
constructor of sub class which should be first
statement.
✔ super(arg-list);
• It is used to call a super class method from sub
class method to avoid redundancy of code
✔ super.addNumbers(a, b);
Super
Super and Hiding

•Why is super needed to access super-class members?


•When a sub-class declares the variables or methods with
the same names and types as its super-class:
class A {
int i = 1;
}
class B extends A {
int i = 2;
System.out.println(“i is “ + i);
}
•The re-declared variables/methods hide those of the
super-class.
Example: Super and Hiding

class A {
int i;
}
class B extends A {
int i;
B(int a, int b) {
super.i = a; i = b;
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
Example: Super and Hiding
•Although the i variable in B hides the i variable in A,
super allows access to the hidden variable of the
super-class:
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
Method Overriding

•When the method in subclass has the same name


and type signature as a method in superclass, then
the method in subclass is said to override the
method in superclass.
•When a overridden method is called from subclass,
it will always refer to the version of the method
defined by subclass, version in superclass is hidden.
Method Overriding Contd.


Usage of Java Method Overriding
⚫Method overriding is used to provide the specific
implementation of a method which is already provided by
its superclass.
⚫Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
⚫The method must have the same name as in the parent
class
⚫The method must have the same parameter as in the
parent class.
⚫There must be an IS-A relationship (inheritance).
Class Demo
Class A
{
Example Class B
{ {
int i, j; int k; public static void main(String ar
A(int a1, int a2) B(int x, int y, int z) {
{ { B ob = new B(2,5,9);
i =a1; super(x,y); ob.display();
j=a2; k =z; }
} } }
void display() void display()
{ {
System.out.println(i+ j); // calling overrriden
} method
} Super.display();

System.out.println(k);
}
}
Dynamic Method Dispatch or Runtime Polymorphism

Method overriding is one of the ways in which Java supports


Runtime Polymorphism. Dynamic method dispatch is the
mechanism by which a call to an overridden method is resolved
at run time, rather than compile time.
•When an overridden method is called through a superclass reference, Java
determines which version(superclass/subclasses) of that method is to be
executed based upon the type of the object being referred to at the time the call
occurs. Thus, this determination is made at run time.
•At run-time, it depends on 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
•A superclass reference variable can refer to a subclass object. This is also
known as upcasting. Java uses this fact to resolve calls to overridden methods
at run time.
Example
class Bank{ //Test class to create objects and call the met
int getRateOfInterest() hods
{ class Test2
return 0; {
} public static void main(String args[])
} {
//Creating child classes. Bank a;
class SBI extends Bank{ //inheritance a=new SBI(); //upcasting
int getRateOfInterest() //overriding System.out.println("SBI Rate of Interest: "+
{ a.getRateOfInterest());
return 8;
} a =new ICICI();
}
class ICICI extends Bank{ System.out.println("ICICI Rate of Interest:
int getRateOfInterest() "+a.getRateOfInterest());
{ }
return 7; }
}

}
Abstract class and Methods
• An abstract class is a class that is declared with abstract keyword.
• An abstract method is a method that is declared without an
implementation.
• An abstract class may or may not have all abstract methods. Some of
them can be concrete methods
• A method defined abstract must always be redefined in the
subclass,thus making overriding compulsory OR either make subclass
itself abstract.
• Any class that contains one or more abstract methods must also be
declared with abstract keyword.
• There can be no object of an abstract class.That is, an abstract class
can not be directly instantiated with the new operator.
• An abstract class can have parametrized constructors and default
constructor is always present in an abstract class.
Example
abstract class Shape class TestAbstraction1{
{ public static void main(String args[])
abstract void draw(); {
} Shape s=new Circle1();
s.draw();
//In real scenario, implementation is provide }
d by others i.e. unknown by end user }

class Rectangle extends Shape{


void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape{
void draw()
{
System.out.println("drawing circle");
}
}
final
•final is a keyword can be used with
1)Variables
final int x = 10; //x acts as a constant, cant change its value
x = 20; //error
2) Classes
//final class cannot be inherited
final class A class B extends A //error
{ {
//statements //statements
} }
3)Methods
//final methods cannot be overridden
class A class B extends A
{ {
final void display() void display() //error
{ {
} }
} }
Object class
Method Purpose
Object clone() Creates a new object that is the same as object being
cloned
boolean Determines whether one object is equal to another
equals(Object object)
Void finalize() Called before an unused object is recycled
int hashCode() Returns the hash code associated with invoking
object
Void notify() Resumes execution of a thread waiting on invoking
object
Void notifyAll() Resumes execution of all threads waiting on invoking
object
Void wait() Waits on another thread of execution
Void wait(long
milliseconds)
TRY

•Create a class Bank which cannot be instantiated. Bank class


contains a method getinterest(). Provide the implementation of
getinterest() in subclasses SBI, PNB. Create tester class to
create objects of both the subclasses and call the method.
Thank You

You might also like