Encapsulation Exercise – 2

2. Write a Java program to create a class called BankAccount with private instance variables accountNumber and balance. Provide public getter and setter methods to access and modify these variables.

class BankAccount{
    private String accountNumber;
    private double balance;

    //setter for accountNumber
    public void setAccountNumber(String accountNumber){
        this.accountNumber=accountNumber;
    }
    //getter for accountNumber
    public String getAccountNumber(){
        return accountNumber;
    }
    //setter for balance
    public void setBalance(double balance){
        this.balance=balance;
    }
    //getter for balance
    public double getBalance(){
        return balance;
    }
}

public class Program
{
    public static void main(String[] args) {
        BankAccount account1=new BankAccount();

        account1.setAccountNumber("2000181");
        account1.setBalance(34672);

        System.out.println("Account Number: "+account1.getAccountNumber());
        System.out.println("Account Balance: "+account1.getBalance());

        
		
	}
}

Leave a Comment