Encapsulation - 2nd
- Using constructor initialize the value of private variable but does not perform Encapsulation.
- To perform Encapsulation using only getter and setter methods.
1. Write a program to set Account Balance using Encapsulation -
import java.util.*;
class Balance {
private String Name;
private int Bal;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getBal() {
return Bal;
}
public void setBal(int Bal) {
if (Bal > 0)
{
this.Bal = Bal;
} else {
System.out.println("\nInvalid Amount...\nYour Account Balance can't be update.");
}
}
}
public class accBalance {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Name: ");
String Name = scan.nextLine();
System.out.print("Enter Deposit Amount: ");
int Bal = scan.nextInt();
Balance obj = new Balance();
obj.setName(Name);
obj.setBal(Bal);
System.out.println("\nName: " +obj.getName()+ "\nBalance: " +obj.getBal());
}
}
Output: -
Tags
Java