> For the complete documentation index, see [llms.txt](https://johch3n611u.gitbook.io/c50108/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201905/20190514-dai-shao-cheng-shi.md).

# 2019/0514/Java\_靜態類別+繼承特性

\#Java類別&物件

### ##Static 類別成員&#xD;

呼叫 ex: Math.PI

不能存取非Static類別成員

![](/files/-LeqxgLVJ9xIss1xVFsG)

This這個參照是屬於動態方法 new 初始化物件 所以 static無法使用 static 屬於編譯時就存在了 new則是new之後才存在

#### ###目的&#xD;

展示動態物件內靜態屬性值

靜態方法只能讀取靜態參數值

動態靜態無法互相呼叫參照

使用靜態方法方式

動態方法new完後應該靜態參數就可以存取

但還是會報錯應該要在 static方法內存取

#### ### EmployeeS&#xD;

```
package com.example.java;

public class EmployeeS {

	private static int count = 0; // number of Employees created

	private String firstName;
	private String lastName;
	public Date birthDate;
	public Date hireDate;

	public EmployeeS(String firstName, String lastName,Date birthDate, Date hireDate) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.birthDate = birthDate;
		this.hireDate = hireDate;

		++count;
		System.out.printf("EmployeeS 物件建立成功 : %s %s; EmployeeS物件數量 = %d%n", firstName, lastName, count);
	}

	public String getFirstName() {
		String strTemp = String.valueOf(this.count);
		return firstName+strTemp;
	}

	public String getLastName() {
		return lastName;
	}

	public static int getCount() {
//		String s1= firstName;
//		String s2;
//		s2 = getFirstName();
		return count;
	}

	public String toString() {
		return String.format("%s,%s-雇用日期: %s-出生日期: %s", lastName, firstName, hireDate, birthDate);
	}

}

```

![](/files/-Leqy21icJ9rfKUhJLRn)

#### ### EmployeeSTest

```
package com.example.java;

public class EmployeeSTest {

	public static void main(String[] args) {
		// TODO 自動產生的方法 Stub

		System.out.printf("新增員工前， EmployeeS物件數量: %d%n", EmployeeS.getCount());

		Date birth = new Date(7, 24, 2005);
		Date hire = new Date(3, 12, 2016);
		EmployeeS e1 = new EmployeeS("李", "連杰", birth, hire);
		EmployeeS e2 = new EmployeeS("甄", "子丹", birth, hire);

		System.out.printf("%n新增員工後， EmployeeS物件數量:%n");
		System.out.printf("呼叫  EmployeeS.getCount(): %d%n", EmployeeS.getCount());

		System.out.printf("%n員工 1: %s %s%n員工2: %s %s%n", e1.getFirstName(), e1.getLastName(), e2.getFirstName(),
				e2.getLastName());

		System.out.println(e1);
	}

}

```

![](/files/-LeqyBSE3wM7r2EJBy5y)

![](/files/-LeqyDxCG-Swm7ZLDHUh)

### ##靜態類別匯入&#xD;

Import 在 c#就是using

![](/files/-LeqyNsenzk8kUPcC9Wm)

#### ### StaticImportTest.java

```
package com.example.java;

import static java.lang.Math.*;
//import static java.lang.Math.sqrt;
//import static java.lang.Math.ceil;

public class StaticImportTest {

	public static void main(String[] args) {
		// TODO 自動產生的方法 Stub
		
	      System.out.printf("呼叫 Math.sqrt,sqrt(900.0) = %.1f%n", sqrt(900.0));
	      System.out.printf("呼叫 Math.ceil,ceil(-9.8) = %.1f%n", ceil(-9.8));
	      System.out.printf("呼叫 Math.E,E = %f%n",  java.lang.Math.E);
	      System.out.printf("呼叫 Math.PI,PI = %f%n", java.lang.Math.PI);

	}

}

```

## #繼承

![](/files/-Leqy_ryFVikvTbuts25)

![](/files/-LeqyfYG4ip59BJF0MCj)

![](/files/-LeqyvyelsfxfuDp4C_x)

#### ##特殊化specialization&#xD;

### ##直接間接父類別

#### ##直接間接父類別direct superclass 上層(一代 (其實有祖類別&#xD;

#### ##間接父類別 indirect superclass &#xD;

#### java元祖類別為 object &#xD;

#### Java只支援單一繼承 跟c++不一樣 sigle inheritance&#xD;

![](/files/-Leqz6Fc9GRjqxlSqE3H)

#### &#xD;

![](/files/-LeqzEPlDkhda9tVYub0)

### ##類別在使用上有兩種狀態&#xD;

Is a relationship

#### ###繼承&#xD;

Has a relationship

#### ###複合&#xD;

![](/files/-LeqzKpS5WyJbImAVJKT)

越子代特徵會越明顯越清楚跟界門綱目科屬種很像

![](/files/-LeqzPawZB9FSHQUdJgI)

![](/files/-LeqzRrw-2QP04Jx93tf)

![](/files/-Leqzc_65ziY0Js4fULg)

### ##向上轉型&#xD;

一般化往上移 ( 通用

特性化往下移

![](/files/-Leqzi-cnSL7EpEJJidS)

### ##繼承-存取權&#xD;

Private 必須要在同一個 class 裡面

Protected 要有繼承關係或同個packge

![](/files/-LeqzncAy7JgDCKuAx-A)

![](/files/-Leqzsov1Q6qRiZo5lFE)

#### ##Entends 繼承&#xD;

#### ###CommissionEmployee.java&#xD;

```
package com.example.java;

public class CommissionEmployee extends Object{
	
	   private final String firstName;                        
	   private final String lastName;                         
	   private final String idNumber;             
	   private double grossSales; 
	   private double commissionRate; // 佣金，抽庸的比例
	                                
	   public CommissionEmployee(String firstName, String lastName, String idNumber, double grossSales, double commissionRate)
	   {                                                                  
	      if (grossSales < 0.0) 
	         throw new IllegalArgumentException("銷售金額必須 >= 0.0");

	      if (commissionRate <= 0.0 || commissionRate >= 1.0)
	         throw new IllegalArgumentException("佣金比例必須 > 0.0 and < 1.0");

	      this.firstName = firstName;                                     
	      this.lastName = lastName;                                    
	      this.idNumber = idNumber;         
	      this.grossSales = grossSales;
	      this.commissionRate = commissionRate;
	   } 

	   public String getFirstName()
	   {
	      return firstName;
	   }

	   public String getLastName()
	   {
	      return lastName;
	   } 

	   public String getIdNumber()
	   {
	      return idNumber;
	   } 

	   public void setGrossSales(double grossSales)
	   {
	      if (grossSales < 0.0) 
	         throw new IllegalArgumentException("銷售金額必須 >= 0.0");

	      this.grossSales = grossSales;
	   } 

	   public double getGrossSales()
	   {
	      return grossSales;
	   } 

	   public void setCommissionRate(double commissionRate)
	   {
	      if (commissionRate <= 0.0 || commissionRate >= 1.0)
	         throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");

	      this.commissionRate = commissionRate;
	   } 

	   public double getCommissionRate()
	   {
	      return commissionRate;
	   } 
	        
	   public double earnings()              
	   {                                     
	      return commissionRate * grossSales;
	   } 

	   @Override
	   public String toString()                                             
	   {                                                                    
	      return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f %n%s: %.2f" ,    
	         "領佣金的員工姓名", firstName, lastName,                    
	         "身分證字號", idNumber,                
	         "每周銷售金額", grossSales,                                     
	         "佣金比例", commissionRate,
	         "薪資",this.earnings());                           
	   } 

}

```

### ##在不夠熟悉時&#xD;通常是實作兩個子類別最後再把相同之處往上搬制做父類別&#xD;

操控CommissionEmployee類別鑄造物件並操控物件進行方法

但其實是準備跟Employee類別做一般化的父類別

#### ### CommissionEmployeeTest.java&#xD;

```
package com.example.java;

public class CommissionEmployeeTest {

	public static void main(String[] args) {
		// TODO 自動產生的方法 Stub
		
		CommissionEmployee employee01 = new CommissionEmployee("劉", "德華", "A123456789", 10000, .06);
		CommissionEmployee employee02 = new CommissionEmployee("陳", "立農", "A123456789", 5000, .1);

		System.out.println("以下呼叫 Get Method 取回員工資料:");
		System.out.printf("%n%s %s%n", "姓:", employee01.getFirstName());
		System.out.printf("%s %s%n", "名:", employee01.getLastName());
		System.out.printf("%s %s%n", "身分證字號:", employee01.getIdNumber());
		System.out.printf("%s %.2f%n", "銷售金額:", employee01.getGrossSales());
		System.out.printf("%s %.2f%n", "佣金比例:", employee01.getCommissionRate());
		
		employee01.setGrossSales(15000);
		employee01.setCommissionRate(.65);

		System.out.printf("%n%s:%n%n%s%n", "更新員工資料後，呼叫 toString Method 取回員工資料:", employee01);
		System.out.printf("%n%s:%n%n%s%n", "第二位員工資料", employee02.toString());


		
	}

}

```

![](/files/-Ler-G34I4fFpvcc8OxB)

### ##建構子不會被繼承

![](/files/-Ler-M_GhML68V1F-bQ1)

### ##不標記@Override也會複寫但最好要加上去&#xD;

{% embed url="<https://matthung0807.blogspot.com/2018/02/java-overload.html>" %}

![](/files/-Ler-TJ9usOUWuldLk7N)

{% embed url="<https://docs.oracle.com/javase/7/docs/api/index.html>" %}

在實作一個子類別 不一樣的地方只有紅色的地方

![](/files/-Ler-_XmNSb3HarAWzeB)

#### ###BasePlusCommissionEmployee.java

#### ##減少重複程式碼

![](/files/-Ler-h9Z3Va_gbumWpoK)

建構子 方法 程式碼幾乎一樣

![](/files/-Ler-lKg3nlOgt4XXwhu)

#### ##防止錯誤 ( 重點為第三點 維護困難

![](/files/-Ler-pk-aUHxwH-uWcHw)

### ##繼承的使用&#xD;

設計繼承架構 從兩個都是繼承object轉成其中一個為父類別，

(BasePlusCommissionEmployee、CommissionEmployee

![](/files/-Ler-wUl7v08x2v3lVbQ)

### #子類別呼叫父類別建構式

![](/files/-Ler01v2g37sB8G7IESd)

### ##初始化new父輩實體變數(參數) super ， c#裡面是base&#xD;

{% embed url="<https://www.google.com/search?q=java+super+c%23&rlz=1C1GCEU_zh-TWTW835TW836&oq=java+super+c&aqs=chrome.3.69i57j0l5.7904j0j7&sourceid=chrome&ie=UTF-8>" %}

#### ###如果沒有寫參數就會自動呼叫沒有參數的版本&#xD;

#### ###super(參數, 參數, 參數…)     super(firstName, lastName, socialSecurityNumber, ◦ grossSales, commissionRate); &#xD;

#### ###Super呼叫方法也可以間接取到父輩的參數   super.getGrossSales&#xD;

#### ###或是把參數從私有改為保護或公有&#xD;

#### ###類別設計好了要在新增一個檔案test做測試&#xD;

#### ###熟了的話可以直接從規格書知道那些要寫在父類(一般化)別那些要寫在子(特殊化)，架構邏輯要清楚&#xD;

![](/files/-Ler0J3o_YoKCVXbj-oa)

#### ###CommissionEmployeeExtV1 ( 父類別 繼承實作&#xD;

```
package com.example.java;

public class CommissionEmployeeExtV1 extends Object{
	
	   private final String firstName;                        
	   private final String lastName;                         
	   private final String idNumber;             
	   private double grossSales; 
	   private double commissionRate; // 佣金，抽庸的比例
	                                
	   public CommissionEmployeeExtV1(String firstName, String lastName, String idNumber, double grossSales, double commissionRate)
	   {                                                                  
	      if (grossSales < 0.0) 
	         throw new IllegalArgumentException("銷售金額必須 >= 0.0");

	      if (commissionRate <= 0.0 || commissionRate >= 1.0)
	         throw new IllegalArgumentException("佣金比例必須 > 0.0 and < 1.0");

	      this.firstName = firstName;                                     
	      this.lastName = lastName;                                    
	      this.idNumber = idNumber;         
	      this.grossSales = grossSales;
	      this.commissionRate = commissionRate;
	   } 

	   public String getFirstName()
	   {
	      return firstName;
	   }

	   public String getLastName()
	   {
	      return lastName;
	   } 

	   public String getIdNumber()
	   {
	      return idNumber;
	   } 

	   public void setGrossSales(double grossSales)
	   {
	      if (grossSales < 0.0) 
	         throw new IllegalArgumentException("銷售金額必須 >= 0.0");

	      this.grossSales = grossSales;
	   } 

	   public double getGrossSales()
	   {
	      return grossSales;
	   } 

	   public void setCommissionRate(double commissionRate)
	   {
	      if (commissionRate <= 0.0 || commissionRate >= 1.0)
	         throw new IllegalArgumentException("佣金比例必須 > 0.0 and < 1.0");

	      this.commissionRate = commissionRate;
	   } 

	   public double getCommissionRate()
	   {
	      return commissionRate;
	   } 
	        
	   public double earnings()              
	   {                                     
	      return commissionRate * grossSales;
	   } 

	   @Override
	   public String toString()                                             
	   {                                                                    
	      return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f %n%s: %.2f" ,    
	         "領佣金的員工姓名", firstName, lastName,                    
	         "身分證字號", idNumber,                
	         "每周銷售金額", grossSales,                                     
	         "佣金比例", commissionRate,
	         "薪資",this.earnings());                           
	   } 

}

```

#### ###BasePlusCommissionEmployeeExtV1 ( 子類別 繼承實作&#xD;

```
package com.example.java;

public class BasePlusCommissionEmployeeExtV1 extends CommissionEmployeeExtV1{
	
	   private double baseSalary; //底薪
	                                
	   public BasePlusCommissionEmployeeExtV1(String firstName, String lastName, String idNumber, double grossSales, double commissionRate,double baseSalary)
	   {                                                                  
	      super(firstName,lastName,idNumber,grossSales,commissionRate);
		   
	      if (baseSalary < 0.0)                      
	          throw new IllegalArgumentException("底薪金額必須 >= 0.0");       

	      this.baseSalary = baseSalary;
	   } 
   
	   public void setBaseSalary(double baseSalary)
	   {
	      if (baseSalary < 0.0)
	         throw new IllegalArgumentException("底薪金額必須 >= 0.0");

	      this.baseSalary = baseSalary;
	   } 

	   public double getBaseSalary()
	   {
	      return baseSalary;
	   } 
	        
	   @Override
	   public double earnings()              
	   {                                     
	      return baseSalary + (super.getCommissionRate() * super.getGrossSales());
	   } 

	   @Override
	   public String toString()                                             
	   {                                                                    
	      return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f %n%s: %.2f" ,    
	         "領佣金的員工姓名", super.getFirstName(),  super.getLastName(),                    
	         "身分證字號", super.getIdNumber(),                
	         "每周銷售金額", getGrossSales(),                                     
	         "佣金比例", getCommissionRate(),
	         "底薪金額", baseSalary);                           
	   } 

}

```

#### ### BasePlusCommissionEmployeeExtV1Test&#x20;

#### ( 現在這個階段都在做類別所以檔案內不會有print必須要用 test檔案內 類別的物件操控做顯示&#xD;

```
package com.example.java;

public class BasePlusCommissionEmployeeExtV1Test {

	public static void main(String[] args) {
		// TODO 自動產生的方法 Stub
		
		BasePlusCommissionEmployeeExtV1 employee01 = new BasePlusCommissionEmployeeExtV1("劉", "德華", "A123456789", 10000, .06,1000);
		CommissionEmployeeExtV1 employee02 = new CommissionEmployeeExtV1("陳", "立農", "A123456789", 5000, .1);

		System.out.println("以下呼叫 Get Method 取回員工資料:");
		System.out.printf("%n%s %s%n", "姓:", employee01.getFirstName());
		System.out.printf("%s %s%n", "名:", employee01.getLastName());
		System.out.printf("%s %s%n", "身分證字號:", employee01.getIdNumber());
		System.out.printf("%s %.2f%n", "銷售金額:", employee01.getGrossSales());
		System.out.printf("%s %.2f%n", "佣金比例:", employee01.getCommissionRate());
		System.out.printf("%s %.2f%n", "底薪金額:", employee01.getBaseSalary());
		
		employee01.setGrossSales(15000);
		employee01.setCommissionRate(0.1);
		employee01.setBaseSalary(2000);

		System.out.printf("%n%s:%n%n%s%n", "更新員工資料後，呼叫 toString Method 取回員工資料:", employee01);
		System.out.printf("總薪資:"+String.valueOf(employee01.earnings()));

		System.out.println("\n\n領獎金員工資料:");
		System.out.printf("%n%s:%n%n%s%n", "呼叫 toString Method 取回員工資料:", employee02);
		
	}

}

```

### ##繼承重點&#xD;

經過一系列以上的操作可以看到繼承後的程式碼少了非常少 (重複的都在父類別了

而且修改只要改源頭不需要一個檔案一個檔案改

接著 V2版本

![](/files/-Ler0Pgb_FnNPfgnlqlj)

![](/files/-Ler0R_Jcdya4PZ_30oI)

保留封裝特性但同時又能存取父類別參數

![](/files/-Ler0Vieosa_mnZiZ6Ut)

孫代也更好的可以存取參數

### ##參數使用保護繼承的問題&#xD;

![](/files/-Ler0_0r_qAIEaPQDX-8)

#### ###參數變成無效直沒經過驗證(因為驗證寫在父輩

![](/files/-Ler0dEMXBcm2g3MySMv)

#### ###修改父類別的內容變成不會影響到子類別&#xD;

#### ###CommissionEmployeeExtV2&#xD;

```
package com.example.java;

public class CommissionEmployeeExtV2 extends Object{
	
	   protected final String firstName;                        
	   protected final String lastName;                         
	   protected final String idNumber;             
	   protected double grossSales; 
	   protected double commissionRate; // 佣金，抽庸的比例
	                                
	   public CommissionEmployeeExtV2(String firstName, String lastName, String idNumber, double grossSales, double commissionRate)
	   {                                                                  
	      if (grossSales < 0.0) 
	         throw new IllegalArgumentException("銷售金額必須 >= 0.0");

	      if (commissionRate <= 0.0 || commissionRate >= 1.0)
	         throw new IllegalArgumentException("佣金比例必須 > 0.0 and < 1.0");

	      this.firstName = firstName;                                     
	      this.lastName = lastName;                                    
	      this.idNumber = idNumber;         
	      this.grossSales = grossSales;
	      this.commissionRate = commissionRate;
	   } 

	   public String getFirstName()
	   {
	      return firstName;
	   }

	   public String getLastName()
	   {
	      return lastName;
	   } 

	   public String getIdNumber()
	   {
	      return idNumber;
	   } 

	   public void setGrossSales(double grossSales)
	   {
	      if (grossSales < 0.0) 
	         throw new IllegalArgumentException("銷售金額必須 >= 0.0");

	      this.grossSales = grossSales;
	   } 

	   public double getGrossSales()
	   {
	      return grossSales;
	   } 

	   public void setCommissionRate(double commissionRate)
	   {
	      if (commissionRate <= 0.0 || commissionRate >= 1.0)
	         throw new IllegalArgumentException("佣金比例必須 > 0.0 and < 1.0");

	      this.commissionRate = commissionRate;
	   } 

	   public double getCommissionRate()
	   {
	      return commissionRate;
	   } 
	        
	   public double earnings()              
	   {                                     
	      return commissionRate * grossSales;
	   } 

	   @Override
	   public String toString()                                             
	   {                                                                    
	      return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f %n%s: %.2f" ,    
	         "領佣金的員工姓名", firstName, lastName,                    
	         "身分證字號", idNumber,                
	         "每周銷售金額", grossSales,                                     
	         "佣金比例", commissionRate,
	         "薪資",this.earnings());                           
	   } 

}

```

#### ###BasePlusCommissionEmployeeExtV2&#xD;

```
package com.example.java;

public class BasePlusCommissionEmployeeExtV2 extends CommissionEmployeeExtV2 {

	protected double baseSalary; // 底薪

	public BasePlusCommissionEmployeeExtV2(String firstName, String lastName, String idNumber, double grossSales,double commissionRate, double baseSalary) {
		super(firstName, lastName, idNumber, grossSales, commissionRate);

		if (baseSalary < 0.0)
			throw new IllegalArgumentException("底薪金額必須 >= 0.0");

		this.baseSalary = baseSalary;
	}

	public void setBaseSalary(double baseSalary) {
		if (baseSalary < 0.0)
			throw new IllegalArgumentException("底薪金額必須 >= 0.0");

		this.baseSalary = baseSalary;
	}

	public double getBaseSalary() {
		return baseSalary;
	}

	@Override
	public double earnings() {
		grossSales = -5000.0;
		return baseSalary + (commissionRate * grossSales);
	}

	@Override
	public String toString() {
	      return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f %n%s: %.2f" ,    
	 	         "領佣金的員工姓名", firstName, lastName,                    
	 	         "身分證字號", idNumber,                
	 	         "每周銷售金額", grossSales,                                     
	 	         "佣金比例", commissionRate,
	 	         "底薪金額", baseSalary);
	}

}

```

#### ###BasePlusCommissionEmployeeExtV2Test&#xD;

```
package com.example.java;

public class BasePlusCommissionEmployeeExtV2Test {

	public static void main(String[] args) {
		// TODO 自動產生的方法 Stub
		
		BasePlusCommissionEmployeeExtV2 employee01 = new BasePlusCommissionEmployeeExtV2("劉", "德華", "A123456789", 10000, .06,1000);
		CommissionEmployeeExtV2 employee02 = new CommissionEmployeeExtV2("陳", "立農", "A123456789", 5000, .1);

		System.out.println("以下呼叫 Get Method 取回員工資料:");
		System.out.printf("%n%s %s%n", "姓:", employee01.getFirstName());
		System.out.printf("%s %s%n", "名:", employee01.getLastName());
		System.out.printf("%s %s%n", "身分證字號:", employee01.getIdNumber());
		System.out.printf("%s %.2f%n", "銷售金額:", employee01.getGrossSales());
		System.out.printf("%s %.2f%n", "佣金比例:", employee01.getCommissionRate());
		System.out.printf("%s %.2f%n", "底薪金額:", employee01.getBaseSalary());
		
		employee01.setGrossSales(15000);
		employee01.setCommissionRate(0.1);
		employee01.setBaseSalary(2000);

		System.out.printf("%n%s:%n%n%s%n", "更新員工資料後，呼叫 toString Method 取回員工資料:", employee01);
		System.out.printf("總薪資:"+String.valueOf(employee01.earnings()));

		System.out.println("\n\n領獎金員工資料:");
		System.out.printf("%n%s:%n%n%s%n", "呼叫 toString Method 取回員工資料:", employee02);
		
	}

}

```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201905/20190514-dai-shao-cheng-shi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
