Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. It helps in protecting the data from outside interference and misuse.
Encapsulation helps in data hiding, improves modularity, and allows for a flexible and maintainable code structure. It also enhances security by restricting access to the internal state of an object.
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age > 0) {
this.age = age;
}
}
}
Console Output:
No direct console output. Encapsulation is a design concept.
In encapsulation, the variables of a class are hidden from other classes and can be accessed only through the methods of their current class. This is known as data hiding.
Data hiding ensures controlled access to the class members, which reduces the risk of data corruption and misuse by external classes.
class Account {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if(amount > 0) {
balance += amount;
}
}
}
Console Output:
No direct console output. Data hiding is a design principle.
By using private fields and providing public getter and setter methods, we can control the access and modification of the fields’ values, ensuring encapsulation.
This approach secures the data from unauthorized access and provides a controlled way to modify it.
class Employee {
private String empId;
private double salary;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
if(salary > 0) {
this.salary = salary;
}
}
}
Console Output:
No direct console output. Encapsulation is implemented in code design.
Access modifiers in Java play a crucial role in encapsulation. They define the scope of access to the class members.
The most common access modifiers are public, private, protected, and default, each serving a different level of access control.
class Car {
private String model;
private int year;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
if(year > 1885) { // The first car was invented around 1885
this.year = year;
}
}
}
Console Output:
No direct console output. Access modifiers control access levels.
Encapsulation and abstraction are both fundamental OOP concepts. While encapsulation is about hiding the internal state, abstraction focuses on exposing only essential features.
Together, they help in creating a clear separation between the interface and implementation, enhancing code readability and maintainability.
abstract class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
abstract void makeSound();
}
Console Output:
No direct console output. Encapsulation and abstraction work together.
Encapsulation is widely used in real-world applications to protect sensitive data and ensure that objects are used correctly.
In banking systems, encapsulation is used to protect customer data and ensure secure transactions.
class BankAccount {
private String accountNumber;
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if(amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if(amount > 0 && amount <= balance) {
balance -= amount;
}
}
}
Console Output:
No direct console output. Encapsulation secures banking operations.
Encapsulation works seamlessly with inheritance by allowing subclasses to inherit methods and fields while still controlling access through access modifiers.
This controlled access ensures that subclasses use the inherited features correctly without exposing or altering the encapsulated data.
class Vehicle {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
class Car extends Vehicle {
private int doors;
public int getDoors() {
return doors;
}
public void setDoors(int doors) {
this.doors = doors;
}
}
Console Output:
No direct console output. Encapsulation aids inheritance design.
Encapsulation ensures that a method or a variable can be used polymorphically while maintaining the integrity of the encapsulated data.
Polymorphism allows for dynamic method binding, where the method to be invoked is determined at runtime, supporting flexible and reusable code.
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
System.out.println("Drawing a circle");
}
}
class Square implements Shape {
public void draw() {
System.out.println("Drawing a square");
}
}
Console Output:
Drawing a circle
Drawing a square
Interfaces in Java provide a way to achieve abstraction and encapsulation by defining a contract that classes must follow, ensuring a consistent structure.
Classes implementing an interface must provide concrete implementations for all methods declared in the interface, promoting encapsulation by restricting access to implementation details.
interface Vehicle {
void start();
void stop();
}
class Bike implements Vehicle {
public void start() {
System.out.println("Bike started");
}
public void stop() {
System.out.println("Bike stopped");
}
}
Console Output:
Bike started
Bike stopped
Java libraries extensively use encapsulation to provide a clean and easy-to-use API while hiding complex implementation details.
The Java Collections Framework uses encapsulation to manage data structures like lists, sets, and maps, providing methods to interact with them without exposing their internal workings.
import java.util.ArrayList;
import java.util.List;
public class LibraryExample {
public static void main(String[] args) {
List books = new ArrayList<>();
books.add("Java Programming");
books.add("Effective Java");
for(String book : books) {
System.out.println(book);
}
}
}
Console Output:
Java Programming
Effective Java
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies