Concept of Inheritance encapsulation and polymorphism
Concept of Inheritance encapsulation and polymorphism
The new class that is created is known as subclass (child or derived class) and the
existing class from where the child class is derived is known as superclass (parent or
base class).
class Animal
// to perform inheritance
In the above example, the Dog class is created by inheriting the methods and fields
from the Animal class.
String name;
class Main
labrador.name = "Rohu";
labrador.display();
labrador.eat();
Output
My name is Rohu
I can eat
In the above example, we have derived a subclass Dog from superclass Animal.
Notice the statements,
labrador.name = "Rohu";
labrador.eat();
Here, labrador is an object of Dog. However, name and eat() are the members of
the Animal class.
Since Dog inherits the field and method from Animal, we are able to access the field
and method using the object of the Dog.
Java Inheritance
Implementation
is-a relationship
In Java, inheritance is an is-a relationship. That is, we use inheritance only if there
exists an is-a relationship between two classes.
For example,
Car is a Vehicle
Orange is a Fruit
Surgeon is a Doctor
Dog is an Animal
Here, Car can inherit from Vehicle, Orange can inherit from Fruit, and so on.
However, if the same method is present in both the superclass and subclass,
what will happen?
In this case, the method in the subclass overrides the method in the superclass. This
concept is known as method overriding in Java.
Example 2: Method overriding in Java Inheritance
class Animal
@Override
class Main
{
labrador.eat();
labrador.bark();
Output
I eat dog food
I can bark
Now when we call eat() using the object labrador, the method inside Dog is called.
This is because the method inside the derived class overrides the method inside the
base class.
Note: We have used the @Override annotation to tell the compiler that we are
overriding a method. However, the annotation is not mandatory.
class Animal
@Override
super.eat();
class Main
labrador.eat();
labrador.bark();
Output
I can eat
I can bark
In the above example, the eat() method is present in both the base
class Animal and the derived class Dog. Notice the statement,
super.eat();
Here, the super keyword is used to call the eat() method present in the
superclass.
We can also use the super keyword to call the constructor of the superclass
from the constructor of the subclass.
class Animal
System.out.println("I am an animal.");
class Main
labrador.name = "Rocky";
labrador.display();
labrador.getInfo();
Output
I am an animal.
My name is Rocky
In the above example, we have created a class named Animal. The class includes a
protected field: name and a method: display().
We have inherited the Dog class inherits Animal. Notice the statement,
labrador.name = "Rocky";
labrador.display();
Here, we are able to access the protected field and method of the superclass using
the labrador object of the subclass.
Why use inheritance?
1. The most important use of inheritance in Java is code reusability. The code that
is present in the parent class can be directly used by the child class.
Types of inheritance
There are five types of inheritance.
1. Single Inheritance
In single inheritance, a single subclass extends from a single superclass. For
example,
2. Multilevel Inheritance
In multilevel inheritance, a subclass extends from a superclass and then the same
subclass acts as a superclass for another class. For example,
Java Multilevel Inheritance
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single superclass. For
example,
Note: Java doesn't support multiple inheritance. However, we can achieve multiple
inheritance using interfaces.
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. For example,
Java Hybrid Inheritance
Here, we have combined hierarchical and multiple inheritance to form a hybrid inheritance.
Java Encapsulation
Encapsulation is one of the key features of object-oriented programming.
Encapsulation refers to the bundling of fields and methods inside a single
class.
It prevents outer classes from accessing and changing fields and methods of
a class. This also helps to achieve data hiding.
class Area
int length;
int breadth;
// constructor to initialize values
this.length = length;
this.breadth = breadth;
class Main
rectangle.getArea();
}
Output
Area: 30
In the above example, we have created a class named Area. The main purpose of this
class is to calculate the area.
Here, the fields and methods can be accessed from other classes as well. Hence, this is
not data hiding.
Note: People often consider encapsulation as data hiding, but that's not entirely true.
Encapsulation refers to the bundling of related fields and methods together. This can be used
to achieve data hiding. Encapsulation in itself is not data hiding.
Why Encapsulation?
1. In Java, encapsulation helps us to keep related fields and methods together,
which makes our code cleaner and easy to read.
For example,
class Person
{
if (age >= 0)
this.age = age;
Here, we are making the age variable private and applying logic inside
the setAge() method. Now, age cannot be negative.
The getter and setter methods provide read-only or write-only access to our class
fields.
For example,
We can also achieve data hiding using encapsulation. In the above example, if we
change the length and breadth variable into private, then the access to these fields is
restricted.
And, they are kept hidden from outer classes. This is called data hiding.
Data Hiding
Data hiding is a way of restricting the access of our data members
by hiding the implementation details.
class Person
// private field
// getter method
return age;
// setter method
this.age = age;
class Main
p1.setAge(24);
Output
My age is 24
If we try to access the age field from the Main class, we will get an
error.
p1.age = 24;
Java Polymorphism
Polymorphism is an important concept of object-oriented programming. It simply means
more than one form.
That is, the same entity (method or operator or object) can perform different operations
in different scenarios.
class Polygon
System.out.println("Rendering Polygon...");
// renders Square
System.out.println("Rendering Square...");
// renders circle
public void render()
System.out.println("Rendering Circle...");
class Main
s1.render();
c1.render();
Output
Rendering Square...
Rendering Circle...
Hence, the render() method behaves differently in different classes. Or, we can
say render() is polymorphic.
Why Polymorphism?
Polymorphism allows us to create consistent code. In the previous example, we can
also create different methods:
This will work perfectly. However, for every shape, we need to create different methods.
It will make our code inconsistent.
To solve this, polymorphism in Java allows us to create a single method render() that
will behave differently for different shapes.
Note: The print() method is also an example of polymorphism. It is used to print values
of different types like char, int, string, etc.
1. Method Overriding
2. Method Overloading
3. Operator Overloading
During inheritance in Java, if the same method is present in both the superclass and the
subclass. Then, the method in the subclass overrides the same method in the
superclass. This is called method overriding.
In this case, the same method will perform one operation in the superclass and another
operation in the subclass. For example,
class Language
@Override
class Main
l1.displayInfo();
Output:
In the above example, we have created a superclass named Language and a subclass
named Java. Here, the method displayInfo() is present in both Language and Java.
Based on the object used to call the method, the corresponding information is printed.
Working of
Java Polymorphism
Note: The method that is called is determined during the execution of the program.
Hence, method overriding is a run-time polymorphism.
In a Java class, we can create methods with the same name if they differ in parameters.
For example,
This is known as method overloading in Java. Here, the same method will perform
different operations based on the parameter.
class Pattern
{
for (int i = 0; i < 10; i++)
System.out.print("*");
System.out.print(symbol);
class Main
d1.display();
System.out.println("\n");
Output:
**********
##########
In the above example, we have created a class named Pattern. The class contains a
method named display() that is overloaded.
Here, the main function of display() is to print the pattern. However, based on the
arguments passed, the method is performing different operations:
prints a pattern of *, if no argument is passed or
prints pattern of the parameter, if a single char type argument is passed.
Note: The method that is called is determined by the compiler. Hence, it is also known
as compile-time polymorphism.
int a = 5;
int b = 6;
// + with numbers
int sum = a + b; // Output = 11
Here, we can see that the + operator is overloaded in Java to perform two
operations: addition and concatenation.
Polymorphic Variables
A variable is called polymorphic if it refers to different values under different
conditions.
Object variables (instance variables) represent the behavior of polymorphic
variables in Java. It is because object variables of a class can refer to objects
of its class as well as objects of its subclasses.
Example: Polymorphic Variables
class ProgrammingLanguage
{
public void display()
{
System.out.println("I am Programming Language.");
}
}
class Java extends ProgrammingLanguage {
@Override
public void display()
{
System.out.println("I am Object-Oriented Programming Language.");
}
}
class Main
{
public static void main(String[] args)
{
// declare an object variable
ProgrammingLanguage pl;
Output:
I am Programming Language.
I am Object-Oriented Programming Language.
In the above example, we have created an object variable pl of
the ProgrammingLanguage class. Here, pl is a polymorphic variable. This is
because,
In statement
pl = new ProgrammingLanguage(), pl refer to the object of
the ProgrammingLanguage
class.
And, in statement
pl = new Java(), pl refer to the object of the Java class.
Abstraction in Java
What is Abstraction in Java?
Abstraction is the concept of object-oriented programming that “shows” only essential attributes and
“hides” unnecessary information. The main purpose of abstraction is hiding the unnecessary details from
the users. Abstraction is selecting data from a larger pool to show only relevant details of the object to the
user. It helps in reducing programming complexity and efforts. It is one of the most important concepts of
OOPs.
Abstraction in OOPs with example:
Suppose you want to create a banking application and you are asked to collect all the information
about your customer. There are chances that you will come up with following information about
the customer
Abstraction in Java
But, not all of the above information is required to create a banking application. So, you need to
select only the useful information for your banking application from that pool. Data like name,
address, tax information, etc. make sense for a banking application which is an Abstraction
example in OOPs
Abstraction Encapsulation
Abstraction in
Object
Oriented
Encapsulation solves it
Programming
implementation level.
solves the
issues at the
design level.
Data
Abstraction in Encapsulation means
Java allows hiding the internal
focussing on details or mechanics
what the of how an object does
information something for security
object must reasons.
contain
It is possible that you DO NOT label Shape class as Abstract and then instantiate it. But
such object will have no use in your code and will open a room for potential errors.
Hence this is not desirable.
What are Abstract Methods in Java?
ABSTRACT METHOD in Java, is a method that has just the method definition but does
not contain implementation. A method without a body is known as an Abstract Method.
It must be declared in an abstract class. The abstract method will never be final
because the abstract class must implement all the abstract methods.
As we all know, the formula for calculating area for rectangle, circle, & triangle is
different. The calculateArea() method will have to be overridden by the inheriting
classes. It makes no sense defining it in the Shape class, but we need to make sure
that all the inheriting classes do have the method.
Such methods can be labeled abstract.
Syntax:
abstract public void calculateArea();
Summary:
Abstraction in Programming is the process of selecting important data sets for
an Object in your software and leaving out the insignificant ones.
Once you have modeled your object using Data Abstraction in Java, the same
set of data could be used in different applications.