201871010116-祁英紅《面向對象程序設計(java)》第七週學習總結

項目html

內容java

《面向對象程序設計(java)》編程

https://www.cnblogs.com/nwnu-daizh/數組

這個做業的要求在哪裏ide

https://www.cnblogs.com/nwnu-daizh/p/11654436.html函數

做業學習目標性能

  1. 掌握四種訪問權限修飾符的使用特色;
  2. 掌握Object類的用途及經常使用API;
  3. 掌握ArrayList類的定義方法及用途;
  4. 掌握枚舉類定義方法及用途;
  5. 結合本章實驗內容,理解繼承與多態性兩個面向對象程序設計特徵,並體會其優勢。

 

實驗內容和步驟學習

實驗1:(20分)測試

程序代碼以下:ui

class Parent {
	private String p1 = "這是Parent的私有屬性";
	public String p2 = "這是Parent的公有屬性";
	protected String p3 = "這是Parent受保護的屬性";
	String p4 = "這是Parent的默認屬性";
	private void pMethod1() {
		System.out.println("我是Parent用private修飾符修飾的方法");
	}
	public void pMethod2() {
		System.out.println("我是Parent用public修飾符修飾的方法");
	}
	protected void pMethod3() {
		System.out.println("我是Parent用protected修飾符修飾的方法");
	}
	void pMethod4() {
		System.out.println("我是Parent無修飾符修飾的方法");
	}
}
class Son extends Parent{
	private String s1 = "這是Son的私有屬性";
	public String s2 = "這是Son的公有屬性";
	protected String s3 = "這是Son受保護的屬性";
	String s4 = "這是Son的默認屬性";
	public void sMethod1() {
		System.out.println(  );//分別嘗試顯示Parent類的p一、p二、p三、p4值
		System.out.println("我是Son用public修飾符修飾的方法");
	}
	private void sMethod2() {
		System.out.println("我是Son用private修飾符修飾的方法");
	}
	protected void sMethod() {
		System.out.println("我是Son用protected修飾符修飾的方法");
	}
	void sMethod4() {
		System.out.println("我是Son無修飾符修飾的方法");
	}	
}
public class Demo {
	public static void main(String[] args) {
		Parent parent=new Parent();
		Son son=new Son();
		System.out.println(  );	//分別嘗試用parent調用Paren類的方法、用son調用Son類的方法	
	}
}  

由於private屬性僅對本類可見,public屬性對全部類可見,protected屬性對本包和全部類可見,默認屬性對本包可見。

而Parent類的p1是Parent的私有屬性,在子類中不能被調用,因此程序出錯,沒法顯示;p2是Parent的公有屬性,p3是Parent受保護的屬性,p4是Parent的默認屬性,這些屬性能在子類中被調用,因此能夠顯示p二、p三、p4的值.

運行過程如圖:

同上。parent類和son類的私有屬性也不能被調用,因此調用p1與s1程序運行錯誤。

用parent調用Paren類的方法運行結果以下:

 

 

 

用son調用Son類的方法運行結果以下:

 

 

 

實驗2:測試程序1(15分)

 5-8程序代碼以下:

package equals;

/**
 * This program demonstrates the equals method.
 * @version 1.12 2012-01-26
 * @author Cay Horstmann
 */
public class EqualsTest
{
   public static void main(String[] args)
   {
      var alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      var alice2 = alice1;
      var alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      var bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);

      System.out.println("alice1 == alice2: " + (alice1 == alice2));

      System.out.println("alice1 == alice3: " + (alice1 == alice3));

      System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));

      System.out.println("alice1.equals(bob): " + alice1.equals(bob));

      System.out.println("bob.toString(): " + bob);

      var carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      var boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);
      System.out.println("boss.toString(): " + boss);
      System.out.println("carl.equals(boss): " + carl.equals(boss));
      System.out.println("alice1.hashCode(): " + alice1.hashCode());
      System.out.println("alice3.hashCode(): " + alice3.hashCode());
      System.out.println("bob.hashCode(): " + bob.hashCode());
      System.out.println("carl.hashCode(): " + carl.hashCode());
   }
}

5-9程序代碼以下:

package equals;

import java.time.*;
import java.util.Objects;

public class Employee
{
   private String name;//private定義了一個只能在該類中訪問的字符串變量
   private double salary;
   private LocalDate hireDay;
//建立私有屬性
   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }//訪問器

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }

   public boolean equals(Object otherObject)
   {
      // a quick test to see if the objects are identical  快速測試這些對象是否相同
      if (this == otherObject) return true;

      // must return false if the explicit parameter is null   若是顯示參數爲空,必須返回false
      if (otherObject == null) return false;

      // if the classes don't match, they can't be equal   若是第幾個類不匹配,則他們不相同
      if (getClass() != otherObject.getClass()) return false;

      // now we know otherObject is a non-null Employee   //其餘對象爲非空Employee類
      var other = (Employee) otherObject;

      // test whether the fields have identical values   //測試是否是有相同值
      return Objects.equals(name, other.name) 
         && salary == other.salary && Objects.equals(hireDay, other.hireDay);
   }

   public int hashCode()
   {
      return Objects.hash(name, salary, hireDay); 
   }

   public String toString() //把其餘類型的數據轉換爲字符串類型的數據
   {
      return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" 
         + hireDay + "]";
   }
}

5-10程序代碼以下:

package equals;

public class Manager extends Employee  //擴展了一個子類Manager
{
   private double bonus; //建立一個私有屬性

   public Manager(String name, double salary, int year, int month, int day)//定義變量
   {
      super(name, salary, year, month, day);//調用了父類的構造器
      bonus = 0;
   }

   public double getSalary()
   {
      double baseSalary = super.getSalary();//更改器
      return baseSalary + bonus;
   }

   public void setBonus(double bonus)
   {
      this.bonus = bonus;
   }

   public boolean equals(Object otherObject)
   {
      if (!super.equals(otherObject)) return false;
      var other = (Manager) otherObject;
      // super.equals checked that this and other belong to the same class  用super.equals檢查這個類和其餘類是否屬於同一個類
      return bonus == other.bonus;
   }

   public int hashCode()
   {
      return java.util.Objects.hash(super.hashCode(), bonus);
   }

   public String toString()//吧其餘類型的數據轉換爲字符串類型的數據
   {
      return super.toString() + "[bonus=" + bonus + "]";
   }
}

5-八、5-九、5-10程序運行結果以下:

 刪除程序中Employee類、Manager類中的equals()hasCode()toString()方法,背錄刪除方法,在代碼錄入中理解類中重寫Object父類方法的技術要點。

equals方法:用於檢測一個對象是否等於另一個對象,在子類中調用equals方法時,首先調用超類的equals,若是檢測失敗,對象就不可能相等,若是超類中的域都相等,就須要比較子類中的實例域。

hashCode方法:散列碼(hash code)是由對象導出的一個整型值,且沒有規律,因爲hashCode方法定義在object類中,所以每一個對象都有一個默認的散列碼,其值是對象的存儲地址該方法返回一個整型數值。

toString方法:用於返回表示對象值的字符串,只要對象與一個字符串經過操做符「+」鏈接起來,Java編譯就會自動地調用toString方法。

 

 Employee類重寫後代碼以下:

package equals;
 
import java.time.*;
import java.util.Objects;
 
public class Employee
{
   private String name;    //建立三個私有屬性
   private double salary;
   private LocalDate hireDay;
 
   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }
 
   public String getName()
   {
      return name;
   }
 
   public double getSalary()
   {
      return salary;
   }
 
   public LocalDate getHireDay()
   {
      return hireDay;
   }
 
   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;   //定義局部變量
      salary += raise;
   }
 
@Override
public int hashCode() {   //重寫hashCode方法,使相等的兩個對象獲取的HashCode也相等
    // TODO Auto-generated method stub
    return Objects.hash(name, salary, hireDay);
}
 
@Override
public boolean equals(Object obj) {
    // TODO Auto-generated method stub
    if (this == obj) return true;     //快速測試幾個類的根是否相同,便是否是同一個超類。這個if語句判斷兩個引用是不是同一個,若是是同一個,那麼這兩個對象確定相等。
    if (obj == null) return false;   //若是顯示參數爲空,則返回false
    if (getClass() !=obj.getClass()) return false;   //用getClass()方法獲得對象的類。若是幾個類不匹配,則它們不相等
 
    //其餘對象是非空Employee類
    //在以上判斷完成,再將獲得的參數對象強制轉換爲該對象,考慮到父類引用子類的對象的出現,而後再判斷對象的屬性是否相同
    Employee other = (Employee) obj;
    //測試字段是否具備相同的值
    return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
 }
 
 
@Override
public String toString() {  //把其餘類型的數據轉爲字符串類型的數據(toString方法能夠自動生成)
    // TODO Auto-generated method stub
    return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
}
 
}

Manager類重寫以後代碼以下:

package equals;
 
public class Manager extends Employee     //子類:Manager類繼承Employee類
{
   private double bonus;     //建立私有屬性bouns
 
   public Manager(String name, double salary, int year, int month, int day)
   {
      super(name, salary, year, month, day);    //子類直接調用超類中已建立的屬性
      bonus = 0;      //給bouns賦初值爲空
   }
 
   public double getSalary()//訪問器
   {
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }
 
   public void setBonus(double bonus)   //更改器
   {
      this.bonus = bonus;
   }
 
   public boolean equals(Object otherObject)   //快速測試幾個類的根是否相同,便是否是同一個超類
   {
      if (!super.equals(otherObject)) return false;
      Manager other = (Manager) otherObject;
       //使用super.equals檢查這個類和其餘是否屬於同一個類
      return bonus == other.bonus;
   }
 
   public int hashCode()    //重寫hashCode方法,使相等的兩個對象獲取的HashCode也相等
   {
      return java.util.Objects.hash(super.hashCode(), bonus);
   }
 
   public String toString()    //把其餘類型的數據轉爲字符串類型的數據(toString方法能夠自動生成)
   {
      return super.toString() + "[bonus=" + bonus + "]";
   }
}

EmployeeTest類代碼以下:

package equals;
 
/**
 * This program demonstrates the equals method.
 * @version 1.12 2012-01-26
 * @author Cay Horstmann
 */
public class EqualsTest
{
   public static void main(String[] args)
   {
      Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      Employee alice2 = alice1;
      Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
 
      System.out.println("alice1 == alice2: " + (alice1 == alice2));
 
      System.out.println("alice1 == alice3: " + (alice1 == alice3));
 
      System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));
 
      System.out.println("alice1.equals(bob): " + alice1.equals(bob));
 
      System.out.println("bob.toString(): " + bob);
 
      Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);
      System.out.println("boss.toString(): " + boss);
      System.out.println("carl.equals(boss): " + carl.equals(boss));
      System.out.println("alice1.hashCode(): " + alice1.hashCode());
      System.out.println("alice3.hashCode(): " + alice3.hashCode());
      System.out.println("bob.hashCode(): " + bob.hashCode());
      System.out.println("carl.hashCode(): " + carl.hashCode());
   }
}

  程序運行結果以下圖:

  

實驗2:測試程序2(15分)

 5-11程序代碼以下:

package arrayList;

import java.util.*;

/**
 * This program demonstrates the ArrayList class.
 * @version 1.11 2012-01-26
 * @author Cay Horstmann
 */
public class ArrayListTest
{
   public static void main(String[] args)
   {
      // fill the staff array list with three Employee objects  用三個Employee類填充staff數組列表
      var staff = new ArrayList<Employee>();   //動態數組,能夠靈活設置數組的大小

      staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
      staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
      staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));

      // raise everyone's salary by 5%   將每一個人的薪水提升5%
      for (Employee e : staff)
         e.raiseSalary(5);

      // print out information about all Employee objects   打印出全部Employee類的信息
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" 
            + e.getHireDay());
   }
}

  

package arrayList;

import java.time.*;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;
 //建立三個私有屬性
   public Employee(String name, double salary, int year, int month, int day)//構造器
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }
//訪問器
   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }//定義兩個局部變量
}

  程序運行結果以下:

 設計適當的代碼,測試ArrayList類的set()、get()、remove()、size()等方法的用法。

package arrayList;
 
import java.util.*;
 
/**
 * This program demonstrates the ArrayList class.
 * @version 1.11 2012-01-26
 * @author Cay Horstmann
 */
public class ArrayListTest
{
   private static final Employee element = null;
   private static final int index = 0;
 
   public static void main(String[] args)
   {
      // fill the staff array list with three Employee objects
      ArrayList<Employee> staff = new ArrayList<Employee>();   //用三個Employee對象填充數組
 
      staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
      staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
      staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
      ArrayList<Employee> list = new ArrayList<Employee>();
       
    //size()的用法
      int size=staff.size();
      System.out.println("arrayList中的元素個數是:"+size);
      for(int i=0;i<staff.size();i++)
      {
          //get()的用法
          Employee e=staff.get(i);
          System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
                    + e.getHireDay());
      }
      //set()的用法
      staff.set(0, new Employee("llx", 20000, 1999, 11, 06));
      Employee e=staff.get(0);
      System.out.println("修改後的數據爲:name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
                + e.getHireDay());
       
      //remove()的用法
      staff.remove(2);
      System.out.println("將第一個數據刪除後:");
      int size1=staff.size();
      System.out.println("arrayList中的元素個數是:"+size1);
      for(int i=0;i<staff.size();i++)
      {
          Employee p=staff.get(i);
          System.out.println("name=" + p.getName() + ",salary=" + p.getSalary() + ",hireDay="
                    + p.getHireDay());
      }
      
      // raise everyone's salary by 5%
      for (Employee e1 : staff)    //把每一個人的薪資提升%5
         e1.raiseSalary(5);
 
      // print out information about all Employee objects
      for (Employee e1 : staff)   //輸出全部僱員對象的信息
         System.out.println("name=" + e1.getName() + ",salary=" + e1.getSalary() + ",hireDay="
            + e1.getHireDay());    //利用getName(),getSalary() 和getHireDay()方法輸出全部僱員對象的信息
   }
}

  程序運行結果如圖:

實驗2:測試程序3(15分)

程序代碼以下:

package enums;

import java.util.*;

/**
 * This program demonstrates enumerated types.
 * @version 1.0 2004-05-24
 * @author Cay Horstmann
 */
public class EnumTest  
{  
   public static void main(String[] args)
   {  
      var in = new Scanner(System.in);
      System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
      String input = in.next().toUpperCase();
      Size size = Enum.valueOf(Size.class, input);  //靜態values方法返回枚舉的全部值的數組
      System.out.println("size=" + size);
      System.out.println("abbreviation=" + size.getAbbreviation());
      if (size == Size.EXTRA_LARGE)
         System.out.println("Good job--you paid attention to the _.");      
   }
}
//定義枚舉類型
enum Size
{
   SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

   private Size(String abbreviation) { this.abbreviation = abbreviation; }
   public String getAbbreviation() { return abbreviation; }

   private String abbreviation;
}//調用構造函數

  程序運行結果以下:

刪除程序中Size枚舉類,背錄刪除代碼,在代碼錄入中掌握枚舉類的定義要求。

 全部的枚舉類型都是Enum類地子類,他們繼承了這個類的許多方法,其中最有用的是toString,這個方法可以返回枚舉常量名。每一個枚舉類型都有一個靜態的values方法,它將返回一個包含所有枚舉值的數組。ordinal方法返回enum聲明中枚舉常量的位置,位置從0開始計數。 

刪除Size枚舉類程序代碼以下:

package enums;

import java.util.*;

/**
 * This program demonstrates enumerated types.
 * @version 1.0 2004-05-24
 * @author Cay Horstmann
 */
public class EnumTest  
{  
   public static void main(String[] args)
   {  
      var in = new Scanner(System.in);
      System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
      String input = in.next().toUpperCase();
      Size size = Enum.valueOf(Size.class, input);  //靜態values方法返回枚舉的全部值的數組
      System.out.println("size=" + size);
      System.out.println("abbreviation=" + size.getAbbreviation());
      if (size == Size.EXTRA_LARGE)
         System.out.println("Good job--you paid attention to the _.");      
   }
}

enum Size
{
   SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

   private Size(String abbreviation) { this.abbreviation = abbreviation; }
   public String getAbbreviation() { return abbreviation; }

   private String abbreviation;
}//調用構造函數

 程序運行結果以下:

實驗2:測試程序4(5分)

程序代碼以下:

public class TestVarArgus {  
    public static void dealArray(int... intArray){  
        for (int i : intArray)  
            System.out.print(i +" ");  
          
        System.out.println();  
    }        
    public static void main(String args[]){  
        dealArray();  
        dealArray(1);  
        dealArray(1, 2, 3);  
    }  
}

  程序運行結果以下:

實驗3:編程練習(10分)

 程序代碼以下:

public class Demo {
	public static void main(String[] args) {
		Son son = new Son();
		son.method();
	}
}

class Parent {
	Parent() {
		System.out.println("Parent's Constructor without parameter");
	}

	Parent(boolean b) {
		System.out.println("Parent's Constructor with a boolean parameter");
	}

	public void method() {
		System.out.println("Parent's method()");
	}
}

class Son extends Parent {
	//補全本類定義
	Son() {
	super(true);    //調用父類有參構造
	    System.out.println("Son's Constructor without parameter");
	}
	public void method() {
	    System.out.println("Son's method()");
	    super.method();
	}
}

  程序運行結果以下:

3. 實驗總結:(15分)

 經過學習繼承這一章的內容以及實驗,掌握了繼承創建類與類間的is-a關係,意味着父類對象變量能夠引用子類對象,在Java中,一個父類能夠有多個子類,但一個子類只能有一個父類,子類經過extends關鍵字來繼承父類,父類和子類的三種繼承方式:1.public繼承,(public成員全部的類均可以訪問);2.private繼承,(private成員只有本類能訪問);3.protect繼承,(protect成員只有本類和子類能訪問)。子類繼承父類是對父類屬性和方法的全面繼承,同時子類在繼承了父類的方法後可對父類的方法進行重寫。父類用做對象的聲明類型,構造器用子類的構造器。object類是Java中全部類的始祖,在Java中每一個類都是由它擴展而來的,若是沒有明確的指出超類,object就被認爲是這個類的超類,

相關文章
相關標籤/搜索