In: Computer Science
java
Objective: Create a class. Create objects. Use methods of a class.
Program
//class BankAccount
class BankAccount
{
//data members
int accountNumber;
double balance;
String customerName;
//constructor without parameters
public BankAccount()
{
accountNumber = 0 ;
balance = 0;
customerName = "";
}
//constructor with three parameters
public BankAccount(int accountNumber, double balance,
String customerName)
{
this.accountNumber =
accountNumber;
this.balance = balance;
this.customerName =
customerName;
}
//constructor that allow to initialize the balance at
a given number
public BankAccount(double balance)
{
this.accountNumber = 0;
this.balance = balance;
customerName = "";
}
//setter methods
public void setAccountNumber(int accountNumber)
{
this.accountNumber =
accountNumber;
}
public void setBalance(double balance)
{
this.balance = balance;
}
public void setCustomerName(String customerName)
{
this.customerName =
customerName;
}
//getter methods
public int getAccountNumber()
{
return accountNumber;
}
public double getBalance()
{
return balance;
}
public String getCustomerName()
{
return customerName;
}
//method withdraw
public void withdraw(double amount)
{
if(balance>amount)
balance -=
amount;
else
System.out.println("Not sufficient balance");
}
//method deposit
public void deposit(double amount)
{
balance += amount;
System.out.println("Balance = " +
balance);
}
//method reset that change the balance to zero
public void resetBalance()
{
balance = 0 ;
}
public String toString()
{
return "Account Number = " +
accountNumber +", Balance = $" +
balance + ",
Customer Name = " + customerName;
}
}
//tester class
class Tester
{
// main method
public static void main (String[] args)
{
//Create one bank account using the
first constructor and print its characteristics.
BankAccount ba1 = new
BankAccount();
System.out.println(ba1);
//Create one bank account using the
second constructor and print its characteristics.
BankAccount ba2 = new
BankAccount(118897, 50000, "John");
System.out.println(ba2);
//Create one bank account using the
third constructor and print its characteristics.
BankAccount ba3 = new
BankAccount(2500);
System.out.println(ba3);
//Deposit 1000 in each bank
account
ba1.deposit(1000);
ba2.deposit(1000);
ba3.deposit(1000);
//Withdraw 500 from the first bank
account, 200 from the second one.
ba1.withdraw(500);
ba2.withdraw(200);
//Change the customer name of the
third account
ba3.setCustomerName("Johny");
}
}
Output
Account Number = 0, Balance = $0.0, Customer Name =
Account Number = 118897, Balance = $50000.0, Customer Name =
John
Account Number = 0, Balance = $2500.0, Customer Name =
Balance = 1000.0
Balance = 51000.0
Balance = 3500.0