Encapsulation
- Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) principles, along with Inheritance, Polymorphism and Abstraction.
- Encapsulation is achieved through the use of access modifiers and getter and setter methods.
- A getter method for read-only access.
- A setter method for write-only access.
Problem: -
import java.util.*;
class Encapsulation {
private String Username, Password, Name;
private int Age;
Encapsulation(String Username, String Password, String Name, int Age) {
this.Username = Username;
this.Password = Password;
this.Name = Name;
this.Age = Age;
}
public String getUsername() {
return Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getAge() {
return Age;
}
public void setAge(int Age) {
this.Age = Age;
}
}
public class Main_Caps {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Please Enter Your Name: ");
String Name = scan.nextLine();
System.out.print("Please Enter Your Username: ");
String Username = scan.nextLine();
System.out.print("Please Enter Your Password: ");
String Password = scan.nextLine();
System.out.print("Please Enter Your Age: ");
int Age = scan.nextInt();
scan.close();
Encapsulation obj = new Encapsulation(Username, Password, Name, Age);
System.out.println("\nUsers Input :-");
System.out.println("\nUsername: " +obj.getUsername()+ "\nPassword: " +obj.getPassword()+ "\nName: " +obj.getName()+ "\nAge: " +obj.getAge());
// Write-Access
obj.setUsername("Mj4480");
obj.setPassword("Mj@#4480");
obj.setName("Mj Mausam");
obj.setAge(25);
System.out.println("\nSystem Input :-");
System.out.println("\nUsername: " +obj.getUsername()+ "\nPassword: " +obj.getPassword()+ "\nName: " +obj.getName()+ "\nAge: " +obj.getAge());
}
}
Output: -
Problem: -
import java.util.*;
class Encapsulation1 {
private String Name;
private int Age;
Encapsulation1 (String Name, int Age) {
this.Name = Name;
this.Age = Age;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getAge() {
return Age;
}
public void setAge(int Age) {
this.Age = Age;
}
}
public class Main_Caps1 {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Your Name: ");
String Name = scan.nextLine();
System.out.print("Enter Your Age: ");
int Age = scan.nextInt();
Encapsulation1 obj = new Encapsulation1(Name, Age);
System.out.println("\nName: " +obj.getName()+ "\nAge: " +obj.getAge());
}
}
Output: -
Tags
Java