Inheritance in Java
CO 3 Apply concept of Inheritance, Interface and package.
The process of obtaining the data members and methods from one class to
another class is known as inheritance. It is one of the fundamental features
of object-oriented programming.
Important points
In the inheritance the class which is give data members and methods
is known as base or super or parent class.
The class which is taking the data members and methods is known
as sub or derived or child class.
The data members and methods of a class are known as features.
The concept of inheritance is also known as re-usability or
extendable classes or sub classing or derivation.
Why use Inheritance ?
It's main uses are to enable polymorphism and to be able to reuse
code for different classes by putting it in a common super class
For code Re-usability
In case of java if we wants to performed inheritance we use the keyword
extends
Syntax of Inheritance
class Subclass-Name extends Superclass-Name
{
//methods and fields
}
Inheriting the feature from base class to derived class
In order to inherit the feature of base class into derived class we use the
following syntax
Syntax
class ClassName_1
{
Variable_1 declaration;
Method_1 declaration;
}
class ClassName-2 extends ClasssName-1 (Logically Linked)
{
Variable_2 declaration; Variable_1 declaration;
Method_2 declaration; Method_1 declaration;
}
The following diagram use view about inheritance.
In the above diagram data members and methods are represented in broken
line are inherited from faculty class and they are visible in student class
logically.
Type of Inheritance
Based on number of ways inheriting the feature of base class into derived
class we have five types of inheritance; they are:
Single inheritance
Multiple inheritance(Not with the help of classes)
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
Single inheritance
In single inheritance there exists single base class and single derived class.
class A (super /Base class)
class B (Derived /Sub class) extends A
Example of Single Inheritance
class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonous=2000;
void totalSal()
{
System.out.println("Actual salary credited into account: "+(salary+bonous));
}
}
class SingleEx
{
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
obj.totalSal();
}
}
Multilevel inheritances in Java
In Multilevel inheritances there exists single base class, single derived class
and multiple intermediate base classes.
Single base class + single derived class + multiple intermediate base
classes.
Intermediate base classes An intermediate base class is one in one context
with access derived class and in another context same class access base class.
class A
class B extends A
class C extends B
class D extends C
Hence all the above three inheritance types are supported by both classes and
interfaces.
Example of Multilevel Inheritance
class Faculty
{
float total_sal=0, salary=30000;
}
class HRA extends Faculty
{
float hra=3000;
}
class DA extends HRA
{
float da=2000;
}
class Science extends DA
{
float bonous=2000;
}
class MultilevelEx
{
public static void main(String args[])
{
Science obj=new Science();
obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonous;
System.out.println("Total Salary is:"+obj.total_sal);
}
}
Hierarchical Inheritance in java
When more than one classes inherit a same class then this is called hierarchical
inheritance. For example class B, C and D extends a same class A.Class
Lets
A see the
diagram representation of this:
{
class B extends A{
class C extends A
As you can see in the above diagram that when a class has more than one child
classes (sub classes) or in other words more than one child classes have the
same parent class then this type of inheritance is known as hierarchical
inheritance.
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Hybrid inheritance
Combination of any inheritance type
In the combination if one of the combination is multiple inheritance then the
inherited combination is not supported by java through the classes concept
but it can be supported through the concept of interface.
OVERLOADING METHODS
In Java it is possible to define two or more methods within the same class that
share the same name, as long as their parameter declarations are different. When
this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading.
Method overloading is one of the ways that Java implements polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call. Thus, overloaded methods must differ in the data type and/or
number of their parameters. While overloaded methods may have different
return types, the return type alone is insufficient to distinguish two versions of a
method. When Java encounters a call to an overloaded method, it simply
executes the version of the method whose parameters match the arguments used
in the call.
// Demonstrate method overloading.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
} // Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
} // Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
} // overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result; // call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
OVERLOADING CONSTRUCTORS
In addition to overloading normal methods, you can also overload constructor
methods. In fact, for most real-world classes that you create, overloaded
constructors will be the norm, not the exception.
Constructor overloading is a concept of having more than one constructor with
different parameters list, in such a way so that each constructor performs a
different task. For e.g. Vector class has 4 types of constructors.
The compiler differentiates these constructors by taking the number of
parameters, and their type.
In other words whenever same constructor is existing multiple times in the same
class with different number of parameters or order of parameters or type of
parameters is known as Constructor overloading.
In general constructor overloading can be used to initialized same or different
objects with different values.
Syntax :
class A
A(){ }
A(int a ,int b){ }
A(int a, double d){ }
Class B
{A a=new A();
A a1=new A(56,89.67);
A a2=new A(90,89);}
class Box
{
double width;
double height;
double depth; // This is the constructor for Box.
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;
}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol; // get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Method Overriding in Java
Whenever same method name is existing in both base class and derived class
with same types of parameters or same order of parameters is known
as method Overriding. Here we will discuss about Overriding in Java.
Note: Without Inheritance method overriding is not possible.
Advantage 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 Method Overriding
Method must have same name as in the parent class.
Method must have same parameter as in the parent class.
Must be IS-A relationship (inheritance).
The data types of the arguments along with their sequence must
have to be preserved as it is in the overriding method.
Example of method overriding in Java
In this example, we have defined the walk 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.
Example
class Walking
{
void walk()
{
System.out.println("Man walking fastly");
}
}
class Man extends Walking
{
void walk()
{
System.out.println("Man walking slowly");
}
}
class OverridingDemo
{
public static void main(String args[])
{
Man obj = new Man();
obj.walk();
}
}
Note: Whenever we are calling overridden method using derived class object
reference the highest priority is given to current class (derived class). We can
see in the above example high priority is derived class.
Note: super. (super dot) can be used to call base class overridden method in
the derived class.
Final keyword in java
It is used to make a variable as a constant, Restrict method overriding,
Restrict inheritance. It is used at variable level, method level and class level.
In java language final keyword can be used in following way.
Final Keyword at Variable Level
Final Keyword at Method Level
Final Keyword at Class Level
Final at variable level
Final keyword is used to make a variable as a constant. This is similar to
const in other language. A variable declared with the final keyword cannot be
modified by the program after initialization. This is useful to universal
constants, such as "PI".
Final Keyword in java Example
public class Circle
{
public static final double PI=3.14159;
public static void main(String[] args)
{
System.out.println(PI);
}
}
Final Keyword at method level
It makes a method final, meaning that sub classes can not override this
method. The compiler checks and gives an error if you try to override the
method.
When we want to restrict overriding, then make a method as a final.
Example
public class A
{
public void fun1()
{
.......
}
public final void fun2()
{
.......
}
}
class B extends A
{
public void fun1()
{
.......
}
public void fun2()
{
// it gives an error because we can not override final method
}
}
Example of final keyword at method level
Example
class Employee
{
final void disp()
{
System.out.println("Hello Good Morning");
}
}
class Developer extends Employee
{
void disp()
{
System.out.println("How are you ?");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}
}
Output
It gives an error
Final Keyword at Class Level
It makes a class final, meaning that the class can not be inheriting by other
classes. When we want to restrict inheritance then make class as a final.
Example
public final class A
{
......
......
}
public class B extends A
{
// it gives an error, because we can not inherit final class
}
Abstract class in Java
We know that every Java program must start with a concept of class that is
without the class concept there is no Java program perfect
In Java programming we have two types of classes they are
Concrete class
Abstract class
Concrete class in Java
A concrete class is one which is containing fully defined methods or
implemented method.
Example
class Helloworld
{
void display()
{
System.out.println("Good Morning........");
}
}
Here Helloworld class is containing a defined method and object can be
created directly.
Create an object
Helloworld obj=new Helloworld();
obj.display();
Every concrete class has specific features and these classes are used for
specific requirement, but not for common requirement.
Java abstract Keyword
The abstract keyword is used to achieve abstraction in Java. It is a non-access
modifier which is used to create abstract class and method.
Abstract method
An abstract method is one which contains only declaration or prototype but it
never contains body or definition. In order to make any undefined method as
abstract whose declaration is must be predefined by abstract keyword.
Syntax
abstract ReturnType methodName(List of formal parameter);
Example
abstract void sum();
abstract void diff(int, int);
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class.
An abstract class is one which is containing some defined method and some
undefined method. In java programming undefined methods are known as
un-Implemented, or abstract method.
class A
void display()
System.out.println(“””);
Syntax }
abstract void get();
abstract class className
}
{
......
}
Example
abstract class A
{
.....
}
If any class have any abstract method then that class become an abstract
class.
Example
class Vehicle
{
abstract void bike();
}
Class Vehicle is become an abstract class because it have abstract Bike()
method.
Make class as abstract class
To make the class as abstract class, whose definition must be preceded by a
abstract keyword.
Example
abstract class Vehicle
{
......
}
Example of abstract class
abstract class Vehicle
{
abstract void speed(); // abstract method
}
class Bike extends Vehicle
{
void speed()
{
System.out.println("Speed limit is 40 km/hr..");
}
}
class Car extends Vehicle
{
void speed()
{
System.out.println(“speed limit is 60 km /hr”);
}
}
class AbstractEx
{
public static void main(String args[])
{
Bike obj = new Bike(); //indirect object creation
obj.speed();
Car c=new Car();
c.speed();
}
}
Create an Object of abstract class
An object of abstract class cannot be created directly, but it can be created
indirectly. It means you can create an object of abstract derived class. You
can see in above example
Example
Vachile obj = new Bike(); //indirect object creation
Important Points about abstract class
Abstract class of Java always contains common features.
Every abstract class participates in inheritance.
Abstract class definitions should not be made as final because
abstract classes always participate in inheritance classes.
An object of abstract class cannot be created directly, but it can be
created indirectly.
All the abstract classes of Java makes use of polymorphism along
with method overriding for business logic development and makes
use of dynamic binding for execution logic.
Advantage of abstract class
Less memory space for the application
Less execution time
More performance
Super keyword in java
Super keyword in java is a reference variable that is used to refer parent class
object. Super is an implicit keyword create by JVM and supply each and
every java program for performing important role in three places.
Super keyword At Variable Level
Super keyword At Method Level
Super keyword At Constructor Level
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
super Keyword at Variable Level
Whenever the derived class inherit base class data members there is a
possibility that base class data member are similar to derived class data
member and JVM gets an ambiguity.
In order to differentiate between the data member of base class and
derived class, in the context of derived class the base class data
members must be preceded by super keyword.
Syntax
super.baseclass datamember name
Example
class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+super.salary);//print base class salary
}
}
class SuperEx
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}
super Keyword at Method Level
The super keyword can also be used to invoke or call parent class method. It
should be use in case of method overriding. In other word super
keyword use when base class method name and derived class method name
have same name.
Example of super keyword at method level
Example
class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}
class Faculty extends Student
{
void message()
{
System.out.println("Good Morning Students");
}
void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message() method
}
}
class SuperEx1
{
public static void main(String args[])
{
Faculty s=new Faculty();
s.display();
}
}
In the above example Student and Faculty both classes have message()
method if we call message() method from Student class, it will call the
message() method of Student class not of Person class because priority of
local is high.
In case there is no method in subclass as parent, there is no need to use super.
In the example given below message() method is invoked from Student class
but Student class does not have message() method, so you can directly call
message() method.
Super Keyword at Constructor Level
The super keyword can also be used to invoke or call the parent class
constructor. Constructor are calling from bottom to top and executing from
top to bottom.
To establish the connection between base class constructor and derived class
constructors JVM provides two implicit methods they are:
Super()
Super(...)
super()
super() It is used for calling super class default constructor from the context
of derived class constructors.
Super keyword used to call base class constructor
Syntax
class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class SuperEx2
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Interface in Java
Interface is similar to class but with the major difference it is collection of
public static final variables (constants) and abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can
be only abstract methods in the interface. It is used to achieve fully
abstraction and multiple inheritance in Java.
Important point regarding Interface
• An interface contains abstract methods and final variables.
• Therefore, it is the responsibility of the class that implements an
interface to supply the code for methods.
• A class can implement any number of interfaces, but cannot extend
more than one class at a time.
• Therefore, interfaces are considered as an informal way of realizing
multiple inheritance in Java.
Why we use Interface ?
It is used to achieve fully abstraction.
By using Interface, you can achieve multiple inheritance in java.
It can be used to achieve loose coupling.
properties of Interface
Each method in an interface is implicitly abstract, so the abstract
keyword is not needed.
Methods in an interface are implicitly public.
All the data members of interface are implicitly public static final.
Behavior of compiler with Interface program
In the above image when we compile any interface program, by default
compiler added public static final before any variable and public
abstract before any method. Because Interface is design for fulfill
universal requirements and to achieve fully abstraction.
Syntax of Interface
To declare interface we use the keyword interface
interface Interface_Name
{
public static final datatype variable_name=value;
public abstract returntype method _name(parameter list……);
}
Differences between a Class and an Interface:
Class Interface
The keyword used to create
The keyword used to create a class is “class” an interface is “interface”
An Inteface cannot be
A class can be instantiated i.e, objects of a instantiated i.e, objects
class can be created. cannot be created.
Classes does not support multiple Inteface supports multiple
inheritance. inheritance.
It cannot inherit a class.(u
cannot inherit a class into
It can be inherit another class. interface)
It can be inherited by a class
It can be inherited by another class using the by using the keyword
keyword ‘extends’. ‘implements’
It cannot contain
It can contain constructors. constructors.
It can contain abstract and non abstract It contains abstract methods
methods. only.
Variables and methods in a class can be All variables and methods in
declared using any access specifier(public, a interface are declared as
private, default, protected) public.
Variables in a class can be static, final or All variables are static and
non final. final.
Declaring Interfaces:
The interface keyword is used to declare an interface.
Example
interface Person
{
datatype variablename=value;
//Any number of final, static fields
returntype methodname(list of parameters or no parameters);
//Any number of abstract method declarations
}
Explanations
In the above syntax Interface is a keyword interface name can be user
defined name the default signature of variable is public static final and
for method is public abstract. JVM will be added implicitly public static
final before data members and public abstract before method.
Example
public static final datatype variable name=value; ----> for data member
public abstract returntype methodname(parameters)---> for method
Inheriting an Interfaces:
A class uses the implements keyword to implement an interface. The
implements keyword appears in the class declaration following the
extends portion of the declaration.
Relationship between class and Interface
Any class can extends another class
Any Interface can extends another Interface.
Any class can Implements another Interface
Any Interface can not extend or Implements any class.
}
Example Interface in Java
interface Person
{
void run();
}
class Employee implements Person
{
public void run()
{
System.out.println("Run fast");
}
}
Rules for implementation interface
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a
class can extend another class.
Multiple Inheritance using interface
Example of Interface in Java
Developer( class) Manager(interface)
Employee(class)
interface Developer
{
void disp();
}
interface Manager
{
void show();
}
class Employee implements Developer, Manager
{
public void disp()
{
System.out.println("Hello Good Morning");
}
public void show()
{
System.out.println("How are you ?");
}
}
class MultipleEx
{
public static void main(String args[])
{
Employee obj=new Employee();
obj.disp();
obj.show();
}
}
Class A Interface B Interface C
Class D extends A implements B,C
Interface B
Class A
Class D extends A implements B Interface C extends B
Class E extends D implements C