You are on page 1of 36

Encapsulation and Inheritance

Encapsulation
• Encapsulation in Java is a mechanism of wrapping the data
(variables) and code acting on the data (methods) together as a
single unit.
• In encapsulation, the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their
current class.
• Therefore, it is also known as data hiding

To achieve encapsulation in Java −


•Declaring the instance variable of the class as private. so that it
cannot be accessed directly by anyone from outside the class.
•Provide public setter and getter methods to modify and view the
variables values.
Advantage of Encapsulation in Java
1.The encapsulated code is more flexible and easy to change with new
requirements.
2.It prevents the other classes to access the private fields.
3.Encapsulation allows modifying implemented code without breaking
other code who have implemented the code.
4.It keeps the data and codes safe from external inheritance. Thus,
Encapsulation helps to achieve security.
5.It improves the maintainability of the application.
6.If you don’t define the setter method in the class then the fields can
be made read-only.
7.If you don’t define the getter method in the class then the fields can
be made write-only.
Disadvantage of Encapsulation in Java
1.The main disadvantage of the encapsulation in Java is it increases the
length of the code and slow shutdown execution.
class Emp {
private String name;
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}
class Main {
public static void main(String args[]) {
Emp e=new Emp();
e.setName(“Dr. Om Prakash Yadav");
System.out.print("Name : " + e.getName());
}
}
INHERITANCE
What is Inheritance in Java
• The technique of creating a new class by using an existing
class functionality is called inheritance in Java.
• In other words, inheritance is a process where a child class
acquires all the properties and behaviors of the parent
class.
• The existing class is called parent class and the new class is
called child class.
What is Is-A relationship in Java
• Is-A relationship in java represents Inheritance. It is
implemented using “extends” keyword. It is used for
code reusability.
Important Terminology:
• Superclass/Parent class - The class from where a
subclass inherits features is called superclass. It is
also called base class or parent class.
• Subclass/Child class- A class that inherits all the
members (fields, method, and nested classes)
from other class is called subclass.
• It is also called a derived class, child class, or
extended class.
• A derived class extends its features by inheriting
all the features of another class, called base class,
and can also add its own features. The base class
remains unchanged.
Creating Subclass in Java
• A subclass can be created by using “extends” keyword. 
• The syntax for declaring a subclass of class is as follows:
class subclassName extends superclassName
{
// Variables of subclass
// Methods of subclass
}
class Calculation {
int z; public void addition(int x, int y) { public static void main(String args[])
z = x + y; {
System.out.println(“ sum :"+z); int a = 20, b = 10;
} My_Cal d = new My_Cal();
public void Subtraction(int x, int y) { d .addition(a, b);
z = x - y; d .Subtraction(a, b);
System.out.println(“Sub :"+z); d.multiplication(a, b);
} }
}
class My_Cal extends Calculation { }
public void multiplication(int x, int y)
{
z = x * y;
System.out.println(“ Product :"+z);
}
Advantage of inheritance
• 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
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hierarchical inheritance
• Hybrid inheritance
Single inheritance
• In single inheritance there exists single base class and single
derived class.

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);
}
}
Multilevel inheritances
• 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.
Multilevel inheritances
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 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;
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);
}
}
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.
Hierarchical Inheritance
• In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one sub class
Hybrid inheritance
• Combination of any inheritance type
Member Access and Inheritance
• Although a subclass includes all of the members of its superclass, it
cannot access those members of the superclass that have been
declared as private.
class A { class Access {
int i; // public by default public static void main(String
private int j; // private to A args[]) {
void setij(int x, int y) { B subOb = new B();
i = x; subOb.setij(10, 12);
j = y; subOb.sum();
} System.out.println("Total is " +
} subOb.total);
class B extends A { }
int total; }
void sum() { REMEMBER A class member that has been
total = i + j; // ERROR, j is not declared as private will remain private to its
accessible here class. It is not accessible by any code outside
} its class, including subclasses.
}
A Superclass Variable Can Reference a Subclass Object

• A reference variable of a superclass can be


assigned a reference to any subclass derived
from that superclass.
Using Super
Using super to Call Superclass Constructors
• A subclass can call a
constructor defined by its class BoxWeight extends
superclass by use of the Box {
following form of double weight;
super(arg_list); BoxWeight(double w,
• Here, arg_list specifies any double h, double d, double
arguments needed by the m) {
constructor in the super(w, h, d);
superclass. weight = m;
}
• super() must always be the }
first statement executed
inside a subclass’
constructor.
Second Use for super
• It always refers to the superclass of the subclass in
which it is used.
• This usage has the following general form:
super.member
• Here, member can be either a method or an
instance variable.
• This second form of super is most applicable to
situations in which member names of a subclass
hide members by the same name in the
superclass.
class A {
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B }
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i); } }
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
} }
When Constructors Are Executed
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
class Main {
public static void main(String args[]) {
B b = new B();
}
}
Method Overriding
• In a class hierarchy, when a method in a
subclass has the same name and type signature
as a method in its superclass, then the method
in the subclass is said to override the method in
the superclass.
• When an overridden method is called from
within its subclass, it will always refer to the
version of that method defined by the subclass.
The version of the method defined by the
superclass will be hidden.
class A {
class Override
int i, j;
A(){} {
A(int a, int b) { public static void main(String
i = a; j = b; args[])
} {
void show() {
B s = new B(1, 2, 3);
System.out.println("i and j: " + i +
" " + j); s.show();
} } }
class B extends A {
int k;
}
B(int a, int b, int c) {
super(a, b);
k = c; }
void show() {
System.out.println("k: " + k);
} }
If you wish to access the superclass version of an
overridden method, you can do so by using super.
class Box {
class DemoBoxWeight {
double width , height, depth;
// constructor used when all dimensions specified public static void main(String args[]) {
Box(double w, double h, double d) { BoxWeight mybox = new
width = w; height = h; depth = d; BoxWeight(1.2,2.3,5.5,4.3);
} double vol;
}
vol = mybox.volume();
// BoxWeight now uses super to initialize its Box
attributes. System.out.println("Volume of
class BoxWeight extends Box { weightbox is " + vol);
double weight; }
// initialize width, height, and depth using super()
}
BoxWeight(double w, double h, double d, double
m) {
super(w, h, d); // call superclass constructor
weight = m;
}
double volume() {
return width * height * depth*weight;
}
}
Which is not a type of inheritance?

a) Single inheritance
b) Double inheritance
c) Hierarchical inheritance
d) Multiple inheritance
Which Method is use to implement multiple inheritance in
Java
a) Interfaces
b) Multithreading
c) Protected methods
d) Private methods

You might also like