DALLASCAO.COM

Site of Cao Shouguang, English to Chinese translator

learn java: set classname as method type


public class SavingsAccount {

	/**
	 * output:
	 * 
	 * 3000
	 * 7000
	 * 10000
	 */
	int balance;
	static int totalBalance;
        //constructor
	SavingsAccount(int balance) {
		this.balance = balance;
	}
        //Classname as method type. User return this
	SavingsAccount deposit(int amount) {
		balance += amount;
		totalBalance = totalBalance + balance;
		return this;
	}
	//method void type
	void printBalance() {
		System.out.println(balance);		
	}
	
	public static void main(String[] args) {
		SavingsAccount myAccount = new SavingsAccount(1000).deposit(2000);
		SavingsAccount yourAccount = new SavingsAccount(2000).deposit(5000);		
		myAccount.printBalance();
		yourAccount.printBalance();
		System.out.println(SavingsAccount.totalBalance);
	}

}

Leave a Comment