王艷 201771010127《面向對象程序設計(Java)》第四周學習總結
第一部分:理論知識。
第四章:對象與類
4.1:類與對象的概念。
類:是構造對象的模板或藍圖。由類構造對象的過程稱為創建類的實例。
對象:想要使用oop,一定要清楚對象的三個特性:
1)對象的行為:對象的行為使用可調用的方法定義的。
·2)對象的狀態:每個對象都保存著描述當前特征的信息。
3)對象標識:如何辨明具有相同行為的相似性。
4.2:類之間的關系。
常見關系有:依賴、聚合、繼承。
4.3:使用預定義類。
已學過的預定義類如math,Math,String,Scanner等。
1)對象與對象變量。
在Java語言中,使用構造器構造新實例。構造器是類中一個特殊的方法,生成並初始化對象,它的方法名與類名相同。
想要構造一個Data對象(定義在java.util中),需要在構造器前加上new操作符:new Data()
Data deadline;該語句錯誤。
可將一個對象變量設置為null,表示該對象變量未引用任何變量,如deadlin=null。
4.4:更改器與訪問器。
更改器:修改實例域。前綴set,更改當前類中的屬性。
訪問器:更改實例域。前綴get。
第二部分:實驗部分。
1、實驗目的與要求
(1) 理解用戶自定義類的定義;
(2) 掌握對象的聲明;
(3) 學會使用構造函數初始化對象;
(4) 使用類屬性與方法的使用掌握使用;
(5) 掌握package和import語句的用途。
2、實驗內容和步驟
實驗1:測試以下程序,掌握文件輸入輸出程序設計技術(文件輸入輸出,教材61-62).
代碼如下:
import java.io.*; import java.util.*; public class FileWriteReadTest { public static void main(String[] args) throws IOException { // 寫入文件演示 PrintWriter out = new PrintWriter("myfile.txt"); out.println("姓名 高數 Java 數據結構 平均成績 總成績"); out.println("張三 20 30 40 0 0"); out.println("李四 50 60 70 0 0"); out.close();// 輸出完畢,需要close // 讀入文件演示 Scanner in = new Scanner(new File("myfile.txt"));// 為myfile.txt這個File創建一個掃描器in int number = 1;// 行號 System.out.println(in.nextLine()); while (in.hasNextLine()) {// 判斷掃描器是否還有下一行未讀取,該循環把文件的每一行都讀出 String line = in.nextLine();// 讀出myfile.txt的下一行 System.out.print("第" + (++number) + "行的內容: "); Scanner linescanner = new Scanner(line);// 行內容建立掃描器 linescanner.useDelimiter(" ");// 使用空格作為分隔符 String name = linescanner.next(); String math = linescanner.next(); String java = linescanner.next(); String ds = linescanner.next(); String avg = linescanner.next(); String total = linescanner.next(); System.out.println("name=" + name + " math=" + math + " java=" + java + " ds=" + ds + " avg=" + avg + " total=" + total); } in.close();// 讀入完畢,最後需要對其進行close。 } }
程序運行結果如下:
實驗2 導入第4章示例程序並測試。
測試程序1:
編輯、編譯、調試運行程序4-2(教材104頁);
結合程序運行結果,掌握類的定義與類對象的用法,並在程序代碼中添加類與對象知識應用的註釋;
嘗試在項目中編輯兩個類文件(Employee.java、 EmployeeTest.java ),編譯並運行程序。
程序如下:(1)EmployeeTest.java
import java.time.*; /** * This program tests the Employee class. * * @version 1.12 2015-05-08 * @author Cay Horstmann */ public class EmployeeTest { public static void main(String[] args) { // 用三個Employee對象填充staff數組 Employee[] staff = new Employee[3]; 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); //將每個人的工資提高5% for (Employee e : staff) e.raiseSalary(5); //打印出員工反對的信息 for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } } 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; } }
程序運行結果如下所示:
(2)Employee.java
/** * @version 1.10 1999-11-13 * @author Cay Horstmann */ public class Employee { private String name; private double salary; public native void raiseSalary(double byPercent); public Employee(String n, double s) { name = n; salary = s; } public void print() { System.out.println(name + " " + salary); } static { System.loadLibrary("Employee"); } }
參考教材104頁EmployeeTest.java,設計StudentTest.java,定義Student類,包含name(姓名)、sex(性別)、javascore(java成績)三個字段,編寫程序,從鍵盤輸入學生人數,輸入學生信息,並按以下表頭輸出學生信息表:姓名、性別、java成績。
程序如下:
import java.util.*; public class StudentTest { public static void main(String[] args) { Student[] staff = new Student[4]; System.out.println("請輸入學生姓名、性別、Java成績"); Scanner in = new Scanner(System.in); for(int i=0;i<staff.length;i++) { staff[i]=new Student(in.next(),in.next(),in.nextInt()); } System.out.println("name"+"sex"+"javascore"); for (Student e: staff) System.out.println(e.getName()+e.getSex()+e.getjavaScore()); } } class Student { private String name; private String sex; private int javascore; public Student(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; } }
程序運行結果如下:
測試程序2:
編輯、編譯、調試運行程序4-3(教材116);
結合程序運行結果,理解程序代碼,掌握靜態域(netxtId)與靜態方法(getNextId)的用法,在相關代碼後添加註釋;
理解Java單元(類)測試的技巧。
程序如下:
/** /** * This program demonstrates static methods. * @version 1.01 2004-02-19 * @author Cay Horstmann */ public class StaticTest { public static void main(String[] args) { //用三個Employee對象填充staff數組 Employee[] staff = new Employee[3]; staff[0] = new Employee("Tom", 40000); staff[1] = new Employee("Dick", 60000); staff[2] = new Employee("Harry", 65000); //打印出員工反對的信息 for (Employee e : staff) { 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 { private static int nextId = 1; private String name; private double salary; private int id; public Employee(String n, double s) { name = n; salary = s; id = 0; } public String getName() { return name; } public double getSalary() { return salary; } public int getId() { return id; } public void setId() { id = nextId; //將此ID設置為下一個可用ID nextId++; } public static int getNextId() { return nextId; //返回static域 } public static void main(String[] args) // unit test { Employee e = new Employee("Harry", 50000); System.out.println(e.getName() + " " + e.getSalary()); } }
程序運行結果如下:
測試程序3:
編輯、編譯、調試運行程序4-4(教材121);
結合程序運行結果,理解程序代碼,掌握掌握Java方法參數的用法,在相關代碼後添加註釋;
程序如下:
/** * This program demonstrates parameter passing in Java. * @version 1.00 2000-01-27 * @author Cay Horstmann */ public class ParamTest { public static void main(String[] args) { //該方法不能修改數值參數 System.out.println("Testing tripleValue:"); double percent = 10; System.out.println("Before: percent=" + percent); tripleValue(percent); System.out.println("After: percent=" + percent); //該方法可以改變對象參數的狀態 System.out.println("\nTesting tripleSalary:"); Employee harry = new Employee("Harry", 50000); System.out.println("Before: salary=" + harry.getSalary()); tripleSalary(harry); System.out.println("After: salary=" + harry.getSalary()); //該方法可以將新對象附加到對象參數 System.out.println("\nTesting swap:"); Employee a = new Employee("Alice", 70000); Employee 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; 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 { 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; } }
程序運行結果如下:
測試程序4:
編輯、編譯、調試運行程序4-5(教材129);
結合程序運行結果,理解程序代碼,掌握Java用戶自定義類的用法,掌握對象構造方法及對象使用方法,在相關代碼後添加註釋。
程序如下:
import java.util.*; /** * This program demonstrates object construction. * @version 1.01 2004-02-19 * @author Cay Horstmann */ public class ConstructorTest { public static void main(String[] args) { //用單個Employee對象填充staff數組 Employee[] staff = new Employee[3]; staff[0] = new Employee("Harry", 40000); staff[1] = new Employee(60000); staff[2] = new Employee(); //打印出員工反對信息 for (Employee e : staff) System.out.println("name=" + e.getName() + ",id=" + e.getId() + ",salary=" + e.getSalary()); } } class Employee { private static int nextId; private int id; private String name = ""; //實例字段初始化 private double salary; // static initialization block static { Random generator = new Random(); //從0-9999隨機分配下一ID的地址 nextId = generator.nextInt(10000); } { id = nextId; nextId++; } public Employee(String n, double s) { name = n; salary = s; } public Employee(double s) { //調用雇員構造函數 this("Employee #" + nextId, s); } //默認構造函數 public Employee() {// salary not explicitly set--initialized to 0 // id initialized in initialization block } public String getName() { return name; } public double getSalary() { return salary; } public int getId() { return id; } }
程序運行結果如下:
測試程序5:
l 編輯、編譯、調試運行程序4-6、4-7(教材135);
l 結合程序運行結果,理解程序代碼,掌握Java包的定義及用法,在相關代碼後添加註釋;
程序4-6如下:
import com.horstmann.corejava.*; import static java.lang.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 Employee 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; //這個文件中的類是這個包的一部分 import java.time.*; //導入語句位於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.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; } }
實驗3 編寫長方形類Rectangle與圓形類Circle,其中Rectangle類設置私有屬性:width,length;Circle類設置私有屬性radius。編寫Rectangle類的帶參構造函數Rectangle(int width,int length), Circle類的帶參構造函數Circle(int radius),編寫兩個類的toString方法(Eclipse可自動生成)。上述2個類均定義以下方法:
求周長的方法public int getPerimeter()
求面積的方法public int getArea()
在main方法中完成以下任務:
(1) 輸入1行長與寬,創建一個Rectangle對象;
(2) 輸入1行半徑,創建一個Circle對象;
(3) 將兩個對象的周長加總輸出,將兩個對象的面積加總輸出。
程序如下:
import java.util.*;
public class Rectangle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("輸入長方形的長:");
Float length = in.nextFloat();
System.out.println("輸入長方形的寬:");
Float width = in.nextFloat();
System.out.println("輸入圓的半徑:");
Float radius = in.nextFloat();
Rec l = new Rec(width, length);
Cir r = new Cir(radius);
System.out.println("矩形周長=" + l.getPerimeter() + "矩形面積=" + l.getArea());
System.out.println("圓周長=" + r.getPerimeter() + "圓面積=" + r.getArea());
float c = l.getPerimeter() + r.getPerimeter();
double s = l.getArea() + r.getArea();
System.out.println("矩形和圓的周長之和:" + c + "矩形和圓的面積之和:" + s);
}
}
class Rec {
private Float width;
private double length;
public Rec(Float w, Float l) {
width = w;
length = l;
}
public Float getPerimeter() {
Float Perimeter = (float) ((width + length) * 2);
return Perimeter;
}
public Float getArea() {
Float Area = (float) (width * length);
return Area;
}
}
class Cir {
private double radius;
double PI = 3.14;
public Cir(Float r) {
radius = r;
}
public Float getPerimeter() {
Float Perimeter = (float) (2 * PI * radius);
return Perimeter;
}
public Float getArea() {
Float Area = (float) (PI * radius * radius);
return Area;
}
}
程序運行結果如下:
實驗總結:本次實驗首先是編譯運行程序了解文件的輸入輸出,在實驗三的基礎上,進一步使用student類編寫了一個Java程序。通過本次實驗,我進一步了解到對象與類的定義以及各自的特點。在之前的學習中,已經了解了幾種預定義類,在這周的學習中,掌握了預定義類的使用。在實驗過程中,還是遇到了很多問題,比如誤將float型相加,而float型加在一起要用強制轉換類型,這是因為基礎知識學習不夠的原因。而對於新學習的知識,有很多地方還是不明白,做實驗時,也是在同學和學長的幫助下,最終才完成了實驗。在以後的學習過程中,自己一一定要多練習寫代碼,提高自己的學習能力。
王艷 201771010127《面向對象程序設計(Java)》第四周學習總結