Bài tập Java OOP: tạo lớp Account giống như theo yêu cầu | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Creat Account class with the following information:

Explanation:

  • Account class describes the information of bank accounts.
  • id, name and balance attributes are the ID account, name of the account and the availabe balance respectively.
  • Account(id: int, name: String) and Account(id: int, name: String, balance: int) are the constructor parameters which is used to declare the corresponding attributes.
  • getId(), setName(), getName(), getBalance() are the setters and getters.
  • deposit(amount: int) method is used to deposit an amount of money (balance += amount).
  • withdraw(amount: int) method is used to withdraw an amount of money (balance -= amount). If the balance in the account is not enough (balance < amount), do not withdraw money. The screen will display as below:
    That amount exceeds your current balance.​
  • display() method is used to display the account information on the screen. To illustrate, if id = 1000, name = "Tuan", balance = 2490, when the display() method is called, it produces the following result:
    Id: 1000
    Name: Tuan
    Balance: 2490​

The below program is used to test Account class:

public class Entry {
	public static void main(String[] args) {
		Account account1 = new Account(1000, "Tuan", 2000);
		account1.display();
		account1.withdraw(2100);
		account1.deposit(600);
		System.out.println("Balance: " + account1.getBalance());
		account1.withdraw(2100);
		System.out.println("Balance: " + account1.getBalance());
	}
}

When the above code is compiled and executed, it produces the following result:

Id: 1000
Name: Tuan
Balance: 2000
That amount exceeds your current balance.
Balance: 2600
Balance: 500

Instruction

public class Account {
	private int id;
	private String name;
	private int balance = 0;

	public Account(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public Account(int id, String name, int balance) {
		this.id = id;
		this.name = name;
		this.balance = balance;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getBalance() {
		return balance;
	}
	public void deposit(int amount) {
		balance += amount;
	}
	public void withdraw(int amount) {
		if(balance >= amount) {
			balance -= amount;		
		}else {
			System.out.println("That amount exceeds your current balance.");
		}
	}
	public void display() {
		System.out.println("Id: " + id);
		System.out.println("Name: " + name);
		System.out.println("Balance: " + balance);
	}
}