訪問器於構造器的高階使用

程式驛站發表於2020-12-13

訪問器

1.屬於封裝的一個分支;用於訪問本類中的私有成員變數
2. 快捷鍵 Alt +Shift+S 然後選擇訪問器快速生產

構造器

1.用於被子類繼承時呼叫
2.規範物件的建立
3.賦值給成員變數並改變此預設值

兩個類關於構造器和訪問器的題

  1. 建立Customer類
package 訪問器的高階練習;

public class Customer {
	private String firstName;
	private String lastName;
	private Account account;//重要的一部分 使這兩個類聯絡
	public Customer() {}
	public Customer(String firstName, String lastName) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public Account getAccount() {
		return account;
	}
	public void setAccount(Account account) {
		this.account = account;
	}
	// toString
	@Override
	public String toString() {
		return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", ID:" + account.getId() + "]";
	}
	
	

}
  1. 建立Account類
package 訪問器的高階練習;

public class Account {
	private int id;
	private double balance;
	private double annuallnterestRate;
	public Account(int id, double balance, double annuallnterestRate) {
		super();
		this.id = id;
		this.balance = balance;
		this.annuallnterestRate = annuallnterestRate;
	}
	public int getId() {
		return id;
	}
	public double getBalance() {
		return balance;
	}
	public double getAnnuallnterestRate() {
		return annuallnterestRate;
	}
	public void setId(int id) {
		this.id=id;
	}
	public void setBalance(double balance) {
		this.balance=balance;
	}
	public void setAnnuallnterestRate(double annuallnterestRate) {
		this.annuallnterestRate=annuallnterestRate;
	}
	public double withdraw(double amount) {
		if(amount>balance) {
			System.out.println("餘額不足");
		}else {
			balance-=amount;
		}
		return amount;
	}
	public void deposit(double amount) {
		balance+=amount;
	}
	//toString的功能就是用來列印使用者所有變數的資訊的;返回值型別不能為空
	// @override
	//public String toString() {
	//	return "saa";
	//}

}
  1. 建立測試類 (關鍵是如何將兩個類聯絡起來以及如何
呼叫Customer的Account類的變數)
package 訪問器的高階練習;

public class CustomerTest {
	public static void main(String[] args) {
		Customer a=new Customer("Jane","Smith");
		Account b=new Account(1000,2000,0.0123);
		a.setAccount(b);//將賬戶賦值給使用者  是他們聯絡
	    Account c =a.getAccount();//獲取該使用者的賬戶並賦值
	    c.deposit(100);
	    c.withdraw(960);
	    c.withdraw(2000);
	    //有toString方法,就可以輸出字串,否則直接是地址
	    //toString方法我寫到了 Customer自定義類中,這個自定義類中含有所有的變數
	    System.out.println(a);
		
	}

相關文章