201871010112-梁麗珍《面向對象程序設計(java)》第四周學習總結

 

項目html

內容java

這個做業屬於哪一個課程編程

<任課教師博客主頁連接>https://www.cnblogs.com/nwnu-daizh/數組

這個做業的要求在哪裏併發

             <做業連接地址>https://www.cnblogs.com/nwnu-daizh/p/11552848.htmldom

做業學習目標ide

  1. 掌握類與對象的基礎概念,理解類與對象的關係;
  2. 掌握對象與對象變量的關係;
  3. 掌握預約義類Date、LocalDate類的經常使用API;
  4. 掌握用戶自定義類的語法規則,包括實例域、靜態域、構造器方法、更改器方法、訪問器方法、靜態方法、main方法、方法參數的定義要求;(重點、難點)
  5. 掌握對象的構造方法、定義方法及使用要求;(重點);
  6. 理解重載概念及用法;
  7. 掌握包的概念及用法;

第一部分:總結第四章理論知識函數

  (1)面對對象程序設計概述工具

  (2)使用預約義類單元測試

    1.類 是具備相同屬性和行爲的一組對象集合

      類是構造程序的基本單元

      類屬於一種抽象數據類型

    2.對象  特性:

        對象的行爲——能夠對對象施加哪些操做

        對象的狀態——當施加那些方法時,對象如何響應?

        對象標識——如何辨別具備相同行爲與狀態的不一樣對象?

    3.類和對象

      類是對象的原型    全部屬於同一類的對象 都具備相同的特性和操做

      類用於定義實體邏輯   對象是實際的實體

      類是概念模型,定義對象的全部特性和所需的操做   對象是具體的

  (3)知識點概況

 

 

 

(4)文檔註釋

    註釋的插入

    類註釋

    方法註釋

    域註釋

    通用註釋

    包與概述註釋

    註釋的抽取

(5)類設計技巧

  1.必定要保證數據私有

  2.必定要對數據初始化

  3.不要在類中使用過多的基本類型

  4.不是全部的域都須要獨立的域訪問器和域更改器

  5.將職責過多的類進行分解

  6.類名和方法名要可以體現他們的職責

  7.優先使用不可變的類

 

第二部分:實驗部分

實驗名稱:實驗三 類與對象的定義及使用

1.  實驗目的:

  (1) 熟悉PTA平臺線上測試環境;

  (2) 理解用戶自定義類的定義;

  (3) 掌握對象的聲明;

  (4) 學會使用構造函數初始化對象;

  (5) 使用類屬性與方法的使用掌握使用;

  (6) 掌握package和import語句的用途。

 

3. 實驗步驟與內容:

實驗1 採用我的帳號登陸https://pintia.cn/使用綁定碼620781加入PTA平臺NWNU-2019CST1教學班(西北師範大學 計算機科學與工程學院 2018級計算機科學與技術),完成《2019秋季西北師範大學面向對象程序設計程序設計能力測試1》,測試時間50分鐘。

目的:

1)掌握Java語言構造基本程序語法知識(ch1-ch3)

2)利用Java語言基本程序設計知識,學習設計開發含有一個主類、類內可有多個方法的應用程序。

要求:

做業1:公民身份證號碼按照GB11643—1999《公民身份證號碼》國家標準編制,由18位數字組成:前6位爲行政區劃分代碼,第7位至14位爲出生日期碼,第15位至17位爲順序碼,第18位爲校驗碼。從鍵盤輸入1個身份證號,將身份證的年月日抽取出來,按年-月-日格式輸出。注意:輸入使用ScannernextLine()方法,以避免出錯。

輸入樣例:

34080019810819327X

輸出樣例:

1981-08-19

代碼以下:

package project1;

import java.util.Scanner;

public class ID {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner s = new Scanner(System.in);
		System.out.println("what is your ID:");
		String ID = s.nextLine();
			int x= Integer.parseInt(ID.substring(6, 10));
			int y= Integer.parseInt(ID.substring(10, 12));
			int z= Integer.parseInt(ID.substring(12, 14));
			System.out.println("Data of birth:" + x + "-" + y + "-" +z);
			s.close();
	}

}

 

運行結果:

 

做業2:studentfile.txt文件內容是某班同窗的學號與姓名,利用此文件編制一個程序,將studentfile.txt文件的信息讀入到內存,並提供兩類查詢功能:(1)輸入姓名查詢學號;(2)輸入學號查詢姓名。要求程序具備友好人機交互界面。

編程建議:

1)從文件中讀入學生信息,能夠編寫以下函數:

public static void StudentsFromFile(String fileName))

2)輸入姓名查找學生學號,能夠編寫以下函數:

public static String findStudent(String name)

3)輸入學號查找學生姓名,能夠編寫以下函數:

public static String findStudent(String ID)

代碼以下:

package Package;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Main {
    private static Student students[];
    public static void main(String[] args) {
        students=new Student[50];
        Scanner in = new Scanner(System.in);
        try {
            readFile("studentfile.txt");
            System.out.println("請選擇操做,1按姓名,2按學號,3退出");
            int i;
            while ((i = in.nextInt()) != 3) {
                switch (i) {
                case 1:
                    System.out.println("請輸入姓名");
                    String name = in.next();
                    Student student = findStudentByName(name);
                    if (student == null) {
                        System.out.println("沒找到");
                    } else {
                        System.out.println(student.toString());
                    }
                    System.out.println("請選擇操做,1按姓名,2按學號,3退出");
                    break;
                case 2:
                    System.out.println("請輸入學號");
                    String id = in.next();
                    Student student1 = findStudentById(id);
                    if (student1 == null) {
                        System.out.println("沒找到");
                    } else {
                        System.out.println(student1.toString());

                    }
                    System.out.println("請選擇操做,1按姓名,2按學號,3退出");
                    break;

                default:
                    System.out.println("輸入有誤");
                    System.out.println("請選擇操做,1按姓名,2按學號,3退出");
                    break;
                }

            }
        } catch (IOException e) {
            // TODO 自動生成的 catch 塊
            e.printStackTrace();
        }finally {
            in.close();
        }

    }

    public static void readFile(String path) throws IOException {
        FileReader reader = new FileReader(path);
        BufferedReader br = new BufferedReader(reader);
        String result;
        int i=0;
        while ((result = br.readLine()) != null) {
            Student student = new Student();
            student.setName(result.substring(13));
            student.setID(result.substring(0,12));
            students[i]=student;
            i++;
        }
        br.close();
    }

    public static Student findStudentByName(String name) {
        for (Student student : students) {
            if (student.getName().equals(name)) {
                return student;
            }
        }
        return null;

    }

    public static Student findStudentById(String Id) {
        for (Student student : students) {
            if (student.getID().equals(Id)) {
                return student;
            }
        }
        return null;

    }
}

class Student {
    private String name;
    private String ID;

    public String getName() {
        return name;
    }

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

    public String getID() {
        return ID;
    }

    public void setID(String iD) {
        ID = iD;
    }

    @Override
    public String toString() {
        // TODO 自動生成的方法存根
        return "姓名是:" + name + "學號是:" + ID;
    }
}

 運行以下:

 

實驗2 導入第4章示例程序並測試。

測試程序1

  編輯、編譯、調試運行程序4-2(教材104頁);

  結合程序運行結果,掌握類的定義與類對象的用法,並在程序代碼中添加類與對象知識應用的註釋;

  嘗試在項目中編輯兩個類文件(Employee.java EmployeeTest.java ),編譯並運行程序。

  參考教材104EmployeeTest.java,設計StudentTest.java,定義Student類,包含name(姓名)、sex(性別)、javascorejava成績)三個字段,編寫程序,從鍵盤輸入學生人數,輸入學生信息,並按如下表頭輸出學生信息表:

  姓名    性別 java成績

 4-2源代碼:

import java.time.*;

/**
 * This program tests the Employee class.
 * @version 1.13 2018-04-10
 * @author Cay Horstmann
 */
public class EmployeeTest
{
   public static void main(String[] args)
   {
      // fill the staff array with three Employee objects (用三個employee對象填充staff數組 )
      Employee[] staff = new Employee[3];					//構造了一個Employee 數組,並填入三個僱員對象

      staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
      staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

      // raise everyone's salary by 5%  (把每一個人的工資提升5% )
      for (Employee e : staff)    		//利用Employee 類的raiseSalary 方法將每一個僱員的薪水提升5%
         e.raiseSalary(5);

      // print out information about all Employee objects
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" 
            + e.getHireDay());		//調用getName 方法,getId方法和getSalary方法將每一個僱員的信息打印出來
   }
}

class Employee				//定義了Employee類
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String n, double s, int year, int month, int day)	//輸入數據
   {
      name = n;
      salary = s;
      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;
   }
}

4-2代碼運行結果:

類的定義與類對象的用法:

類是對象的抽象,而對象是類的具體實例。類是抽象的,不佔用內存,而對象是具體的,佔用存儲空間。

對象是經過new className產生的,用來調用類的方法;類的構造方法 。

  類的語法

  class 類名{

      屬性

      行爲

      }

類名和文件名要一致,首字母要大寫,若是類名是多個單詞構成,那麼每個單詞首字母都大寫。

根據類來建立對象

  語法:

    類名(數據類型) 變量名 = new 類名();

  給對象賦值屬性語法:

    對象的變量.屬性 = 具體值;

  類的對象的方法的調用:

    對象的變量名字.方法名(參數);

使用」.」運算符訪問對象的屬性和方法。定義方法:對象.屬性:表示調用類之中的屬性; 對象.方法():表示調用類之中的方法。

 

編譯Employee.java代碼:

package project4;

import java.time.LocalDate;

public class Employee {
	 private String name;
	   private double salary;
	   private LocalDate hireDay;

	   public Employee(String n, double s, int year, int month, int day)	//輸入數據
	   {
	      name = n;
	      salary = s;
	      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;
	   }
}

運行結果:

編譯EmployeeTest.java代碼:

package project4;

public class EmployeeTest {
	public static void main(String[] args)
	   {
	      // fill the staff array with three Employee objects (用三個employee對象填充staff數組 )
	      Employee[] staff = new Employee[3];					//構造了一個Employee 數組,並填入三個僱員對象

	      staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
	      staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
	      staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

	      // raise everyone's salary by 5%  (把每一個人的工資提升5% )
	      for (Employee e : staff)    		//利用Employee 類的raiseSalary 方法將每一個僱員的薪水提升5%
	         e.raiseSalary(5);

	      // print out information about all Employee objects
	      for (Employee e : staff)
	         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" 
	            + e.getHireDay());		//調用getName 方法,getId方法和getSalary方法將每一個僱員的信息打印出來
	   }
}

 運行結果:

設計StudentTest.java的源代碼:

package project4;

import java.util.Scanner;

public class StudentTest {		//定義StudentTest類
	private String name;
	private String sex;
	private int javascore;
	
	public StudentTest(String n, String s, int j)	//輸入數據
	{
		name = n;
		sex = s;
		javascore = j;
	}
	public String getName()		//讀取名字
	{
		return name;
	}
	public String getSex()		//讀取性別
	{
		return sex;
	}
	public int getJavascore()	//讀取成績
	{
		return javascore;
	}
	public static void main(String[] args)
	{
		System.out.println("請輸入學生人數:");
		Scanner in = new Scanner(System.in);
		int number = in.nextInt();
		StudentTest[] score = new StudentTest[number];		//構造了一個StudentTest數組
		for (int i=0;i<number;i++)
		{
			System.out.println("第"+(i+1)+"個學生輸入信息"+"姓名:");
				String name = in.next();
			System.out.println("性別:");
				String sex = in.next();
			System.out.println("java成績:");
				int j = in.nextInt();
				score[i] = new StudentTest(name,sex,j);
		}
		for(int r=0;r<number;r++)
		{
			System.out.println("姓名:"+score[r].getName()+"\t"+"性別:"+score[r].getSex()+"\t"+"java成績:"+score[r].getJavascore());
		}			//打印信息
		in.close();
	}
}

運行結果:

 

測試程序2

   編輯、編譯、調試運行程序4-3(教材116);

  結合程序運行結果,理解程序代碼,掌握靜態域(netxtId)與靜態方法(getNextId)的用法,在相關代碼後添加註釋;

   理解Java單元(類)測試的技巧。

程序4-3源代碼:

 

/**
 * This program demonstrates static methods.
 * @version 1.02 2008-04-10
 * @author Cay Horstmann
 */
public class StaticTest
{
   public static void main(String[] args)
   {
      // fill the staff array with three Employee objects  (用三個employee對象填充staff數組 )
	  Employee[] staff = new Employee[3];				//構造了一個Employee 數組,並填入三個僱員對象

      staff[0] = new Employee("Tom", 40000);
      staff[1] = new Employee("Dick", 60000);
      staff[2] = new Employee("Harry", 65000);

      // print out information about all Employee objects	(打印有關全部員工對象的信息 )
      for (Employee e : staff)       //調用getName 方法,getId方法和getSalary方法將每一個僱員的信息打印出來
      {
         e.setId();
         System.out.println("name=" + e.getName() + ",id=" + e.getId() + ",salary="
            + e.getSalary());						
      }

      int n = Employee.getNextId(); // calls static method	(經過類名調用靜態方法 )
      System.out.println("Next available id=" + n);
   }
}

class Employee					//構造了一個Employee類
{
   private static int nextId = 1;     //添加了一個靜態域nextId

   private String name;     //實例域定義
   private double salary;
   private int id;

   public Employee(String n, double s)     //構造器定義
   {
      name = n;
      salary = s;
      id = 0;
   }

   public String getName()        //實例域name的訪問器方法
   {
      return name;
   }

   public double getSalary()    //實例域Salary的訪問器方法
   {
      return salary;
   }

   public int getId()          //實例域Id的訪問器方法
   {
      return id;
   }

   public void setId()
   {
      id = nextId; // set id to next available id	(將id設置爲下一個可用id )
      nextId++;
   }

   public static int getNextId()        //實例域NextId的訪問方法
   {
      return nextId; // returns static field	(返回靜態字段)
   }

   public static void main(String[] args) // unit test	(單元測試 )  main方法測試
   {
	  Employee e = new Employee("Harry", 50000);
      System.out.println(e.getName() + " " + e.getSalary());
   }
}

實驗結果:

靜態域(netxtId)與靜態方法(getNextId)的用法

  1.靜態域
若是將域定義爲static,每一個類只有一個這樣的域。而每個對象對於全部的實例域都有本身的一份拷貝。

例如,假定須要給每個記僱員賦予唯一的標識
碼。這裏給Employee類添加一個實例域id和一個靜態域nextId:
class Employee{
 private int id;
 private static int nextId = 1;
}

如今,每個僱員對象都有一個本身的id域,但這個類的全部實例將共享一個nextId域。換句話說,若是有1000個Employee對象,則有1000個實例域id。可是,只有一個靜態nextId。即便沒有一個僱員對象,靜態域nextId也是存在的。它屬於類,而不屬於任何獨立的對象.

  2.靜態方法

靜態方法是一種不能向對象實施操做的方法。

例如,Math類的pow方法就是一個靜態方法。Math.pow(x,a)計算x的a次冪。在計算時,不使用任何Math對象。由於靜態方法不能操做對象,因此不能在靜態方法中訪問實例域。可是,靜態方法能夠訪問自身類中的靜態域。

示例:
public static int getNextId(){
 return nextId;//return static field
}

能夠經過類名調用這個方法:  int n = Employee.getNextId();

在下面兩種狀況使用靜態方法:

(1)一個方法不須要訪問對象的狀態,其所需參數都是經過顯示參數來提供(例如:Math.pow())。
(2)一個方法只須要訪問類的靜態域(例如:Employee.getNextId)。

 

Java單元(類)測試的技巧

單元測試(unit testing),是指對軟件中的最小可測試單元進行檢查和驗證。好比咱們能夠測試一個類,或者一個類中的一個方法。

單元測試好處:它是一種驗證行爲、設計行爲、編寫文檔的行爲、具備迴歸性。

JUnit跟用main方法測試區別:

JUnit的結果更加直觀,直接根據狀態條的顏色便可判斷測試是否經過,而用main方法你須要去檢查他的輸出結果,而後跟本身的指望結果進行對比,才能知道是否測試經過。

JUnit讓咱們同時運行多個測試變得很是方便。

 

測試程序3

  編輯、編譯、調試運行程序4-4(教材121);

  結合程序運行結果,理解程序代碼,掌握Java方法參數的用法,在相關代碼後添加註釋;

4-4源代碼:

 

/**
 * This program demonstrates parameter passing in Java.
 * @version 1.01 2018-04-10
 * @author Cay Horstmann
 */
public class ParamTest
{
   public static void main(String[] args)
   {
      /*
       * Test 1: Methods can't modify numeric parameters  (測試1:方法沒法修改數值參數 )
       */
      System.out.println("Testing tripleValue:");
      double percent = 10;								//按值調用
      System.out.println("Before: percent=" + percent);
      tripleValue(percent);
      System.out.println("After: percent=" + percent);

      /*
       * Test 2: Methods can change the state of object parameters (測試2:方法能夠改變對象參數的狀態 )
       */
      System.out.println("\nTesting tripleSalary:");
      var harry = new Employee("Harry", 50000);
      System.out.println("Before: salary=" + harry.getSalary());
      tripleSalary(harry);
      System.out.println("After: salary=" + harry.getSalary());

      /*
       * Test 3: Methods can't attach new objects to object parameters   (測試3:方法不能將新對象附加到對象參數 )
       */
      System.out.println("\nTesting swap:");
      var a = new Employee("Alice", 70000);
      var b = new Employee("Bob", 60000);
      System.out.println("Before: a=" + a.getName());
      System.out.println("Before: b=" + b.getName());
      swap(a, b);										//實現交換數據的效果
      System.out.println("After: a=" + a.getName());
      System.out.println("After: b=" + b.getName());
   }

   public static void tripleValue(double x) // doesn't work  (不工做)
   {
      x = 3 * x;							//將一個參數值增長至3倍
      System.out.println("End of method: x=" + x);
   }

   public static void tripleSalary(Employee x) // works  (工做)
   {
      x.raiseSalary(200);						//對象引用做爲參數,可實現將一個僱員的薪金提升兩倍的操做
      System.out.println("End of method: salary=" + x.getSalary());
   }

   public static void swap(Employee x, Employee y)
   {
      Employee temp = x;		//交換兩個對象
      x = y;
      y = temp;
      System.out.println("End of method: x=" + x.getName());
      System.out.println("End of method: y=" + y.getName());
   }
}

class Employee // simplified Employee class  (簡化員工類別 )		定義了一個Employee類
{
   private String name;
   private double salary;

   public Employee(String n, double s)		//輸入數據
   {
      name = n;
      salary = s;
   }

   public String getName()			//讀取名字
   {
      return name;
   }

   public double getSalary()		//讀取薪水
   {
      return salary;
   }

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

運行結果:

Java 中方法參數的使用狀況:

一個方法不能修改一個基本數據類型的參數 (即數值型或布爾型)。

一個方法能夠改變一個對象參數的狀態。

一個方法不能讓對象參數引用一個新的對象。

 

測試程序4

  編輯、編譯、調試運行程序4-5(教材129);

  結合程序運行結果,理解程序代碼,掌握Java用戶自定義類的用法,掌握對象構造方法及對象使用方法,在相關代碼後添加註釋。

程序4-5源代碼:

 

import java.util.*;

/**
 * This program demonstrates object construction.
 * @version 1.02 2018-04-10
 * @author Cay Horstmann
 */
public class ConstructorTest
{
   public static void main(String[] args)
   {
      // fill the staff array with three Employee objects   (用三個employee對象填充staff數組 )
      var staff = new Employee[3];					////構造了一個Employee 數組,並填入三個僱員對象

      staff[0] = new Employee("Harry", 40000);
      staff[1] = new Employee(60000);
      staff[2] = new Employee();

      // print out information about all Employee objects  (打印有關全部員工對象的信息 )
      for (Employee e : staff)    
         System.out.println("name=" + e.getName() + ",id=" + e.getId() + ",salary="
            + e.getSalary());		////調用getName 方法,getId方法和getSalary方法將每一個僱員的信息打印出來
   }
}

class Employee						//定義了一個Employee類
{
   private static int nextId;       //靜態域nextId

   private int id;
   private String name = ""; // instance field initialization(實例字段intialization)
   private double salary;
  
   // static initialization block  (靜態intialization塊)
   static					//標記關鍵字static
   {
      var generator = new Random();
      // set nextId to a random number between 0 and 9999   (將nextId設置爲0到999之間的隨機值)
      nextId = generator.nextInt(10000);		//將僱員的ID的起始值賦予一個小於10000的隨機整數
   }

   // object initialization block    (對象intialization塊)
   {
      id = nextId;
      nextId++;
   }

   // three overloaded constructors   //三個重載的構造
   public Employee(String n, double s)
   {
      name = n;
      salary = s;
   }

   public Employee(double s)
   {
      // calls the Employee(String, double) constructor   
      this("Employee #" + nextId, s);   //調用this關鍵字,調用同一類的另外一個構造器。
      									//當調用new Employee(60000)時,Employee(double)構造器將調用Employee(String, double)構造器
   }

   // the default constructor      //錯誤的構造器
   public Employee()
   {
      // name initialized to ""--see above
      // salary not explicitly set--initialized to 0
      // id initialized in initialization block
   }

   public String getName()   //實例域name的訪問器方法
   {
      return name;
   }

   public double getSalary()  //實例域Salary的訪問器方法
   {
      return salary;
   }

   public int getId()    //實例域Id的訪問器方法
   {
      return id;
   }
}

 

運行結果:

Java用戶自定義類的用法

自定義類:

1. 一種是java中已經定義好的類,如以前用過的Scanner類、Random類,直接拿過來用就能夠了。

2.  另外一種是須要咱們本身去定義的類,咱們能夠在類中定義多個方法和屬性來供咱們實際的使用。

定義類的格式

public class 類名{

         定義屬性:

    事物的基本特徵,能夠經過變量來定義屬性,好比人的姓名:private String name = 「張飛」;

    修飾符 數據類型 變量名 = 值;

   定義方法:

       用來定義該事物的具體功能的。

       修飾符 返回值類型 方法名(參數列表){

 

    }

  }

對象構造方法及對象使用方法

  構造方法就是類構造對象時調用的方法,主要用來實例化對象。

  使用new + 構造方法 建立一個對象。

  構造方法與類同名且沒有返回值。

 

測試程序5

  編輯、編譯、調試運行程序4-64-7(教材135);

  結合程序運行結果,理解程序代碼,掌握Java包的定義及用法,在相關代碼後添加註釋;

程序4-6源代碼:

 

import com.horstmann.corejava.*; 		//import語句導入包

// the Employee class is defined in that package  (Employees類在該包中定義)

import static java.lang.System.*;   //靜態導入System類

/**
 * This program demonstrates the use of packages.
 * @version 1.11 2004-02-19
 * @author Cay Horstmann
 */
public class PackageTest
{
   public static void main(String[] args)
   {
      // because of the import statement, we don't have to use 
      // com.horstmann.corejava.Employee here
      var harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);

      harry.raiseSalary(5);

      // because of the static import statement, we don't have to use System.out here
      out.println("name=" + harry.getName() + ",salary=" + harry.getSalary());
   }
}

 

運行結果:

程序4-7源代碼:

package com.horstmann.corejava;    //將類放入包中

// the classes in this file are part of this package   (這個文件中的類就是這個包中的一部分)

import java.time.*;   //java.time包的引入

// import statements come after the package statement   (import語句位於package語句以後)

/**
 * @version 1.11 2015-05-08
 * @author Cay Horstmann
 */
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用來引用當前對象
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);     
   }

   public String getName()    //實例域name的訪問器方法
   {
      return name;
   }

   public double getSalary()   //實例域Salary的訪問器方法
   {
      return salary;
   }

   public LocalDate getHireDay()   //實例域HireDay的訪問器方法
   {
      return hireDay;
   }

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

運行結果:

 

Java包的定義及用法:

1.包的本質就屬於一個文件夾,用來解決類名稱重名的問題。

關鍵字:package

打包編譯命令:  javac -d . 類名.java

-d: 表示生成目錄, 根據package定義生成

. :表示在當前所在目錄生成子目錄

2.包的導入

關鍵字:import

自動匹配編譯順序(在當前目錄下按照主類的使用狀況自動編譯)

javac -d . ./*.java

3.系統經常使用包

  java.lang:系統經常使用基礎類(String Object 包裝類),JDK1.1以後自動導入

  java.utiljava提供的工具程序包(集合類, ArrayList MashMap),須要手工導入

  jucjava.util.concurrent:併發程序包

4.訪問控制權限

private  < default(包訪問權限) < protected (繼承訪問權限)< public

 

4. 實驗總結:

    經過本次實驗,掌握了類與對象的基礎概念,理解類與對象的關係,對象與對象變量的關係,預約義類DateLocalDate類的經常使用API,戶自定義類的語法規則,包括實例域、靜態域、構造器方法、更改器方法、訪問器方法、靜態方法、main方法、方法參數的定義要求,對象的構造方法、定義方法及使用要求,重載概念及用法,包的概念及用法。有些地方理解的還不透徹。對於程序設計的做業,導入studentfile.txt文件的這個編程,感受還不是很明白,難度較大。這章對象與類的學習是個重點,仍須要多加努力下功夫,才能真正掌握吧,繼續努力啊。

相關文章
相關標籤/搜索