Académique Documents
Professionnel Documents
Culture Documents
It’s way to protect our data from the outside world. It means if I made my instance variable public, then anyone
can change its state. But if we make our instance variable private/protected then actually we are restricting
outside entities from making changes to it.
If a data member is declared "private", then it can only be accessed within the same class. No outside class can
access data member of that class. If we need to access these variables, we have to use public "getter" and
"setter" methods.
Getter and Setter's methods are used to create, modify, delete and view the variables values.
class Account{
private int account_number;
private int account_balance;
// getter method
public int getBalance() {
return this.account_balance;
}
// setter method
public void setNumber(int num) {
this.account_number = num;
}
}
In above example, getBalance() method is getter method that reads value of variable account_balance and
setNumber() method is setter method that sets or update value for variable account_number.
Abstraction
Abstraction = different implementations of the same interface.
Abstraction means making things general i.e., instead of creating a very specific class when we create base
classes or interfaces and then implement them to get our specific class.
So here for Lion class we have a generalized class i.e., Animal. This represents abstraction
@Override
public String getType() {
return this.animalType;
}
}
Encapsulation in Java
Encapsulation is a mechanism of binding code and data together in a single unit.
All the methods and variables are wrapped together in a single class.
Set the instance variables private so that these private variables cannot be accessed directly by other classes.
Set getter and setter methods of the class as public so that we can set and get the values of the fields.
SAMPLE PROGRAM.
File-1: EncapsulationClassOne.java
public class EncapsulationClassOne {
All data member (variables) are declared as private. That means it can only be accessed within the same
class. Other class cannot access these private variables.
To access these private variables from other classes, we used public getter and setter methods such as
getAge(), getName(), setAge(), setName(). So, the data can be accessed by public methods when we can set
the variables private and hide their implementation from other classes.
This way we call encapsulation as data hiding.
Encapsulation = information hiding = data hiding.
Weather class contains corresponding getter or setter Methods or not and this weather this methods are
declared as public or not” This things we are not required to check.
class Account{