Inheritance in Java
Inheritance in Java is a mechanism in which one object
acquires all the properties and behaviors of a parent object. It is an
important part of OOPs
The idea behind inheritance in Java is that we can create
new classes that are built upon existing classes. When we inherit from an
existing class, we can reuse methods and fields of the parent class. Moreover,
we can add new methods and fields in your current class also.
Inheritance
·
Using inheritance, you can create a
general class that defines traits 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.
·
Therefore, a subclass is a
specialized version of a superclass.
·
It inherits all of the instance
variables and methods defined by the superclass and adds its own, unique
elements.
Important terminology:
·
Super Class:
The class whose
features are inherited is known as super class(or a base class or a parent
class).
·
Sub Class:
The
class that inherits the other class is known as sub class(or a derived class,
extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
·
Reusability:
Inheritance
supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we
can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
Inheritance Basics
To inherit a class use
the extends keyword
The general form of a class
declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name
{
// body of class
}
Types
of Inheritance in Java
·
Multilevel Inheritance
·
Multiple Inheritance
·
Hierarchical Inheritance
·
Hybrid Inheritance
Single Inheritance
In single inheritance, subclasses inherit the
features of one superclass. In image below, the class A serves as a base class
for the derived class B.
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
class
two extends one
{
public
void print_for()
{
System.out.println("for");
}
}
//
Driver class
public
class Main
{
public
static void main(String[] args)
{
two
g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
For
Geeks
Multilevel Inheritance
In Multilevel
Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class. In below image, the
class A serves as a base class for the derived class B, which in turn serves as
a base class for the derived class C. In Java, a class cannot directly access
the grandparent’s members.
class one
{
public
void print_geek()
{
System.out.println("Geeks");
}
}
class
two extends one
{
public
void print_for()
{
System.out.println("for");
}
}
class
three extends two
{
public
void print_geek()
{
System.out.println("Geeks");
}
}
//
Drived class
public
class Main
{
public
static void main(String[] args)
{
three
g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
Hierarchical Inheritance
In
Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one sub class.In below image, the class A serves as a base class for
the derived class B,C and D
Multiple Inheritance
(Through
Interfaces) :
In Multiple inheritance
,one class can have more than one superclass and inherit features from all
parent classes. Please note that Java does not support multiple
inheritance with classes. In java, we can achieve multiple inheritance
only through Interfaces. In image below, Class C is derived from interface
A and B.
Hybrid Inheritance
(Through
Interfaces) :
It is a mix of two or more of the
above types of inheritance. Since java doesn’t support multiple inheritance
with classes, the hybrid inheritance is also not possible with classes. In
java, we can achieve hybrid inheritance only through Interfaces.
using super
·
Whenever a subclass needs to refer to
its immediate superclass, it can do so by use of the keyword super.
·
super has two general forms.
§ The
first calls the superclass’ constructor.
§ The
second is used to access a member of the superclass that
has been hidden by a member of a subclass
Using super to Call Superclass Constructors
A
subclass can call a constructor method defined by its superclass by use of the
following
form of super:
super(parameter-list);
Here,
parameter-list specifies any parameters needed by the constructor in
the
superclass. super( ) must always be the first statement executed inside a
subclass’
constructor.
//
A complete implementation of BoxWeight.
class
Box {
private
double width,height,depth;
//
construct clone of an object
Box(Box
ob) { // pass object to constructor
width
= ob.width;
height
= ob.height;
depth
= ob.depth;
}
//
constructor used when all dimensions specified
Box(double
w, double h, double d) {
width
= w;
height
= h;
depth
= d;
}
//
constructor used when no dimensions specified
Box()
{
width
= -1; // use -1 to indicate
height
= -1; // an uninitialized
depth
= -1; // box }
//
constructor used when cube is created
Box(double
len) {
width
= height = depth = len;
}
//
compute and return volume
double
volume() {
return
width * height * depth; }
}
//
BoxWeight now fully implements all constructors.
class
BoxWeight extends Box {
double
weight; // weight of box
//
construct clone of an object
BoxWeight(BoxWeight
ob) { // pass object to constructor
super(ob);
weight
= ob.weight;
}
//
constructor when all parameters are specified
BoxWeight(double
w, double h, double d, double m) {
super(w,
h, d); // call superclass constructor
weight
= m;
}
//
default constructor
BoxWeight()
{
super();
weight
= -1;
}
//
constructor used when cube is created
BoxWeight(double
len, double m) {
super(len);
weight
= m; }
}
class
DemoSuper {
public
static void main(String args[]) {
BoxWeight
mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight
mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight
mybox3 = new BoxWeight(); // default
BoxWeight
mycube = new BoxWeight(3, 2);
BoxWeight
myclone = new BoxWeight(mybox1);
double
vol;
vol
= mybox1.volume();
System.out.println("Volume
of mybox1 is " + vol);
System.out.println("Weight
of mybox1 is " + mybox1.weight);
System.out.println();
vol
= mybox2.volume();
System.out.println("Volume
of mybox2 is " + vol);
System.out.println("Weight
of mybox2 is " + mybox2.weight);
System.out.println();
vol
= mybox3.volume();
System.out.println("Volume
of mybox3 is " + vol);
System.out.println("Weight
of mybox3 is " + mybox3.weight);
System.out.println();
vol
= myclone.volume();
System.out.println("Volume
of myclone is " + vol);
System.out.println("Weight
of myclone is " + myclone.weight);
System.out.println();
vol
= mycube.volume();
System.out.println("Volume
of mycube is " + vol);
System.out.println("Weight
of mycube is " + mycube.weight);
System.out.println();
}
}
This
program generates the following output:
Volume of mybox1 is
3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is
0.076
Volume of mybox3 is -1.0
Weight of mybox3 is -1.0
Volume of myclone is
3000.0
Weight of myclone is
34.3
Volume of mycube is 27.0
Weight of mycube is 2.0
Overriding in Java
In any object-oriented programming language, Overriding
is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes
or parent classes. When a
method in a subclass has the same name, same parameters or signature and same
return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.
In other words, it is the type of the object
being referred to that determines which version of an overridden method
will be executed.
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).
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike extends Vehicle
{
public static void main(String args[])
{
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Example of method overriding
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely
Dynamic Method Dispatch or Runtime Polymorphism
in Java
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.
Abstract class in Java
·
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.
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided 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");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction
{
public static void main(String args[])
{
Shape s=new Circle1();
//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}
output
drawing circle
Interface in Java
·
An interface in java is
a blueprint of a class.
·
It is used to achieve multiple
inheritance in Java.
·
It has static constants and abstract
methods.
·
interfaces can have abstract methods and
variables. It cannot have a method body.
·
It cannot be instantiated just like the
abstract class.
syntax
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
By using the keyword implements and interface is
extended to a class
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Multiple inheritance in Java by interface
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
No comments:
Post a Comment