CHAPTER 4
Inheritance
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.
Syntax of Inheritance
class Subclass-Name extends Superclass-Name
{
//methods and fields
}
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.
Advantage of inheritance
If we develop any application, using concept of Inheritance than that application have following
advantages,
Application development time is less.
Application take less memory.
Application execution time is less.
Application performance is enhance (improved).
Redundancy (repetition) of the code is reduced or minimized so that we get
consistence results and less storage cost.
Types of Inheritance
Based on number of ways inheriting the feature of base class into derived class we have the
fallowing types:
Single inheritance
Multiple inheritance
Single inheritance
In single inheritance there exists single base class and single derived class.
Multiple inheritance
In multiple inheritance, there exist multiple classes and single derived class.
The concept of multiple inheritance is not supported in java through concept of classes but it can
be supported through the concept of interface.
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-2 extends ClasssName-1
{
variable declaration;
Method declaration;
}
Explanation
1. ClassName-1 and ClassName-2 represents name of the base and derived classes
respectively.
2. Extends is one of the keyword used for inheriting the features of base class into
derived class it improves the functionality of derived class.
Important Points for Inheritance:
In java, programming one derived class can extends only one base class because java
programming does not support multiple inheritance through the concept of classes,
but it can be supported through the concept of Interface.
Whenever we develop any inheritance, application first create an object of bottom
most derived class but not for top most base class.
When we create an object of bottom most derived class, first we get the memory space
for the data members of top most base class, and then we get the memory space for
data member of other bottom most derived class.
Bottom most derived class contains logical appearance for the data members of all top
most base classes.
If we do not want to give the features of base class to the derived class then the
definition of the base class must be preceded by final hence final base classes are not
reusable or not inheritable.
If we are do not want to give some of the features of base class to derived class then
such features of base class must be as private hence private features of base class are
not inheritable or accessible in derived class.
Data members and methods of a base class can be inherited into the derived class but
constructors of base class cannot be inherited because every constructor of a class is
made for initializing its own data members but not made for initializing the data
members of other classes.
An object of base class can contain details about features of same class but an object of
base class never contains the details about special features of its derived class (this
concept is known as scope of base class object).
For each and every class in java there exists an implicit predefined super class called
java.lang.Object. because it providers garbage collection facilities to its sub classes for
collecting un-used memory space and improved the performance of java application.
Example of Inheritance
class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonous=2000;
public static void main(String[] args)
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
}
}
Output
Salary is: 30000.0
Bonous is: 2000.0
Why multiple inheritance is not supported in java?
Due to ambiguity problem java does not support mutiple inheritance at class level.
Example
class A
{
void disp()
{
System.out.println("Hello");
}
}
class B
{
void disp()
System.out.println("How are you ?");
}
}
class C extends A,B //suppose if it were
{
Public Static void main(String[] args)
{
C obj=new C();
obj.disp();//Now which disp() method would be invoked?
}
}
In above code we call both class A and class B disp() method then it confusion which class
method is call. So due to this ambiguity problem in java do not use multiple inheritance at class
level, but it support at interface level.
Overloading
Whenever same method name is exiting multiple times in the same class with different number of
parameter or different order of parameters or different types of parameters is known as method
overloading.
Different ways to overload the method
There are two ways to overload the method in java
By changing number of arguments or parameters
By changing the data type
By changing number of arguments
In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
Example
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String[] args)
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}
Output
30
60
By changing the data type
In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two float arguments.
Example
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}
Output
30
25.25
Note: The scope of overloading is within the class.
Any object reference of class can call any of overloaded method.
Overriding
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.
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).
Example of method overriding
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");
}
}
public static void main(String[] args)
{
Man obj = new Man();
obj.walk();
}
}
Output
Man walking slowly
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.
Difference between Overloading and Overriding
Overloading Overriding
Whenever same method or Constructor is Whenever same method name is existing
existing multiple times within a class either with multiple time in both base and derived class
1 different number of parameter or with different with same number of parameter or same
type of parameter or with different order of type of parameter or same order of
parameter is known as Overloading. parameters is known as Overriding.
Arguments of method must be different at least Argument of method must be same
2
arguments. including order.
3 Method signature must be different. Method signature must be same.
Private, static and final methods can be Private, static and final methods can not be
4
overloaded. override.
Access modifiers point of view not reduced
5 Access modifiers point of view no restriction.
scope of Access modifiers but increased.
Also known as compile time polymorphism or Also known as run time polymorphism or
6
static polymorphism or early binding. dynamic polymorphism or late binding.
Overloading can be exhibited both are method Overriding can be exhibited only at method
7
and constructor level. leve.
The scope of Overriding is base class and
8 The scope of overloading is within the class.
derived class.
Overloading can be done at both static and Overriding can be done only at non-static
9
non-static methods. method.
For overloading methods return type may or For overriding method return type should be
10
may not be same. same.
Abstract classes
Abstract class
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.
Syntax:
Abstract class ClassName{
………..
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);
Example of abstract class
abstract class Vachile
{
abstract void speed(); // abstract method
}
class Bike extends Vachile
{
void speed()
{
System.out.println("Speed limit is 40 km/hr..");
}
public static void main(String[] args)
{
Vachile obj = new Bike(); //indirect object creation
obj.speed();
}
}
Output
Speed limit is 40 km/hr..
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 participate in inheritance.
Abstract classes 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
Example of abstract class having method body
abstract class Vachile{
abstract void speed();
void mileage()
{
System.out.println("Mileage is 60 km/ltr..");
}}
class Bike extends Vachile{
void speed(){
System.out.println("Speed limit is 40 km/hr..");
}
public static void main(String[] args){
Vachile obj = new Bike();
obj.speed();
obj.mileage();
} }
Output
Mileage is 60 km/ltr..
Speed limit is 40 km/hr..
Example of abstract class having constructor, data member, methods
abstract class Vahicle{
int limit=40;
Vahicle(){
System.out.println("constructor is invoked");
}
void getDetails(){
System.out.println("it has two wheels");
}
abstract void run();
}
class Bike extends Vahicle{
void run(){
System.out.println("running safely..");
}
public static void main(String[] args){
Vachile obj = new Bike();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}}
Output
constructor is invoked
running safely..
it has two wheels
40
Difference between abstract class and concrete class
Concrete class Abstract class
Concrete class are used for specific Abstract class are used for fulfill common
requirement requirement.
Object of abstract class can not be create
Object of concrete class can be create directly.
directly (can create indirectly).
Concrete class containing fully defined methods Abstract class have both undefined method
or implemented method. and defined method.
Final keyword in java
In java language, final keyword can be used in following way.
Final at variable level
Final at method level
Final 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.
The program cannot modify a variable declared with the final keyword after initialization. This is
useful to universal constants, such as "PI".
Example
public class Circle{
public static final double PI=3.14159;
public static void main(String[] args) {
System.out.println(PI);
}}
Final at method level
It makes a method final, meaning that sub classes cannot override this method. The compiler
checks and gives an error if you try to override the method.When we want to restrict overriding,
and then make a method as a final.
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 ?");
}
public static void main(String[] args){
Developer obj=new Developer();
obj.disp();
}}
Output
It gives an error
Final at class level
It makes a class final, meaning that the class cannot be inheriting by other classes. When we
want to restrict inheritance then make class as a final.
Example of final keyword at class level
Example
final class Employee{
{
int salary=10000;
}
class Developer extends Employee{
void show(){
System.out.println("Hello Good Morning");
}
public static void main(String[] args){
Developer obj=new Developer();
Developer obj=new Developer();
obj.show();
}}
Output
Output:
It gives an error
CHAPTER 5
Interface
Interface is similar to class which 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.
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
It is implicitly abstract. So we no need to use the abstract keyword when declaring an
interface.
Each method in an interface is also 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.
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
Implementing 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.
Example
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.
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 cannot extend or Implements any class.
Difference between Abstract class and Interface
Abstract class Interface
It is collection of abstract method and
1 It is collection of abstract method.
concrete methods.
There properties can be reused commonly There properties commonly usable in any
2
in a specific application. application of java environment.
3 It does not support multiple inheritance. It support multiple inheritance.
Abstract class is preceded by abstract
4 It is preceded by Interface keyword.
keyword.
Which may contain either variable or
5 Which should contains only constants.
constants.
The default access specifier of abstract There default access specifier of interface
6
class methods are default. method are public.
These class properties can be reused in These properties can be reused in any other
7
other class using extend keyword. class using implements keyword.
Inside abstract class we can take Inside interface we cannot take any
8
constructor. constructor.
For the abstract class there is no restriction For the interface it should be compulsory to
9 like initialization of variable at the time of initialization of variable at the time of variable
variable declaration. declaration.
For the interface variable cannot declare
There are no any restriction for abstract
10 variable as private, protected, transient,
class variable.
volatile.
There are no any restriction for abstract For the interface. method cannot declare
11 class method modifier that means we can method as strictfp, protected, static, native,
use any modifiers. private, final, synchronized.
Example of Interface
interface Person
{
void run(); // abstract method
}
class A implements Person
{
public void run()
{
System.out.println("Run fast");
}
public static void main(String[] args)
{
A obj = new A();
obj.run();
}
}
Output
Run fast
Multiple Inheritance using interface
Example
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 ?");
}
public static void main(String[] args)
{
Employee obj=new Employee();
obj.disp();
obj.show();
}
}
Output
Hello Good Morning
How are you ?
Encapsulation
Encapsulation is a process of wrapping of data and methods in a single unit is called
encapsulation. Encapsulation is achieved in java language by class concept.
Combining of state and behavior in a single container is known as encapsulation. In java
language encapsulation can be achieve using class keyword, state represents declaration of
variables on attributes and behavior represents operations in terms of method.
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other methods, when
we make a data private then these data only use within the class, but these data not accessible
outside the class.
Real life example of Encapsulation
The common example of encapsulation is capsule. In capsule all medicine are encapsulated in
side capsule.
Benefits of encapsulation
Provides abstraction between an object and its clients.
Protects an object from unwanted access by clients.
Example: A bank application forbids (restrict) a client to change an Account's balance.
Let's see the Example of Encapsulation in java
Example
class Employee
{
private String name;
public String getName()
{
return name;
}
public void setName(String name){
this.name=name;
}
public static void main(String[] args)
{
Employee e=new Employee();
e.setName("Harry");
System.out.println(e.getName());
}
}
Output
Harry
Polymorphism in Java
The process of representing one form in multiple forms is known as Polymorphism.
Here original form or original method always resides in base class and multiple forms represents
overridden method which resides in derived classes.
Polymorphism is not a programming concept but it is one of the principal of OOPs. For many
objects oriented programming language polymorphism principle is common but whose
implementations are varying from one objects oriented programming language to another object
oriented programming language.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
Real life example of polymorphism
Suppose if you are in class room that time you behave like a student, when you are in market at
that time you behave like a customer, when you at your home at that time you behave like a son
or daughter, Here one person present in different-different behaviors.
How to achieve Polymorphism in Java ?
In java programming the Polymorphism principal is implemented with method overriding concept
of java.
Polymorphism principal is divided into two sub principal they are:
Static or Compile time polymorphism
Dynamic or Runtime polymorphism
Note: Java programming does not support static polymorphism because of its limitations and
java always supports dynamic polymorphism.
Let us consider the following diagram
In the above diagram the sum method which is present in BC class is called original form and the
sum() method which are present in DC1 and DC2 are called overridden form hence Sum()
method is originally available in only one form and it is further implemented in multiple forms.
Hence Sum() method is one of the polymorphism method.
Example of runtime polymorphism.
In below example we create two class Person an Employee, Employee class extends Person
class feature and override walk() method. We are calling the walk() method by the reference
variable of Parent class. Since it refers to the subclass object and subclass method overrides the
Parent class method, subclass method is invoked at runtime. Here method invocation is
determined by the JVM not compiler, So it is known as runtime polymorphism.
Syntax
class Person
{
void walk()
{
System.out.println("Can Run....");
}
}
class Employee extends Person{
void walk(){
System.out.println("Running Fast...");
}
public static void main(String[] args){
Person p=new Employee(); //upcasting
p.walk();
}
}
Output
Running fast...
Dynamic Binding
Dynamic binding always says create an object of base class but do not create the object of
derived classes. Dynamic binding principal is always used for executing polymorphic applications.
The process of binding appropriate versions (overridden method) of derived classes which are
inherited from base class with base class object is known as dynamic binding.
Advantages of dynamic binding along with polymorphism with method overriding are.
Less memory space
Less execution time
More performance
Static polymorphism
The process of binding the overloaded method within object at compile time is known as Static
polymorphism due to static polymorphism utilization of resources (main memory space) is poor
because for each and every overloaded method a memory space is created at compile time when
it binds with an object. In C++ environment the above problem can be solve by using dynamic
polymorphism by implementing with virtual and pure virtual function so most of the C++ developer
in real worlds follows only dynamic polymorphism.
Dynamic polymorphism
In dynamic polymorphism method of the program binds with an object at runtime the advantage of
dynamic polymorphism is allocating the memory space for the method (either for overloaded
method or for override method) at run time.
Conclusion
The advantage of dynamic polymorphism is effective utilization of the resources, so java always
use dynamic polymorphism. Java does not support static polymorphism because of its limitation.