201771010112羅松《面向對象程序設計(java)》第六周學習總結
實驗六 繼承定義與使用
實驗目的與要求:
在軟件開發中,通過繼承機制,可以利用已有的數據類型來定義新的數據類型。所定義的新的數據類型不僅擁有新定義的成員,而且還同時擁有舊的成員。因此,類的繼承性使所建立的軟件具有開放性開放性、可擴充性,這是信息組織與分類的行之有效的方法,通過類的繼承關系,使公共的特性能夠共享,簡化了對象、類的創建工作量,增加了代碼的可重用性。運行時多態性是面向對象程序設計代碼重用的一個最強大機制,
二、(1) 理解繼承的定義;(2) 掌握子類的定義要求(3) 掌握多態性的概念及用法;(4) 掌握抽象類的定義及用途;(5) 掌握類中4個成員訪問權限修飾符的用途;(6) 掌握抽象類的定義方法及用途;
2、實驗內容和步驟
實驗1: 導入第5章示例程序,測試並進行代碼註釋。
測試程序1:在elipse IDE中編輯、調試、運行程序5-1 (教材152頁-153頁) ;掌握子類的定義及用法;結合程序運行結果,理解並總結OO風格程序構造特點,理解Employee和Manager類的關系子類的用途,並在代碼中添加註釋。
測試實驗結果如下:
插入此程序的代碼並對其進行註釋,進行更深一步的理解
ManaManager
Emloyee:
子類的定義:在有繼承關系的類中extends前面的類則是子類。
超類和子類都是Java程序員常用的兩個類。
測試程序2:
編輯、編譯、調試運行教材PersonTest程序(教材163頁-165頁);
掌握超類的定義及其使用要求;
掌握利用超類擴展子類的要求;
在程序中相關代碼處添加新知識的註釋。
超類:如果在程序中沒有明確的之處超類,Object就是被認為是這個類的超類,如:Public class Employee extebds Object.在java中,每個類都是Object類擴展而來的。當然也可以使用Object類型的變量引用任何類型的對象。
超類擴展子類的要求
代碼的註釋:
測試程序3:
編輯、編譯、調試運行教材程序5-8、5-9、5-10,結合程序運行結果理解程序(教材174頁-177頁);
掌握Object類的定義及用法;
在程序中相關代碼處添加新知識的註釋。
Employee.java:
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;
}
public boolean equals(Object otherObject)
{
// 看看這些對象是否相同
if (this == otherObject) return true;
// 如果顯式參數為空,則必須返回false
if (otherObject == null) return false;
// 如果類不匹配,它們就不能相等
if (getClass() != otherObject.getClass()) return false;
// 現在我們知道otherObject是一個非空雇員
Employee other = (Employee) otherObject;
// 測試字段是否具有相同的值
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
+ "]";
}
}
Manager.java:
package equals;
public class Manager extends Employee//子類Manager繼承父類Employee
{
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;
Manager other = (Manager) otherObject;
// 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 + "]";
}
}
Equals.java:
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());
}
}
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());
}
}
測試程序4:
在elipse IDE中調試運行程序5-11(教材182頁),結合程序運行結果理解程序;
掌握ArrayList類的定義及用法;
在程序中相關代碼處添加新知識的註釋。
插入程序相關代碼
ArrayList.java:
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)
{
// 用三個Employee對象填充staff數組列表
ArrayList<Employee> staff = new ArrayList<>();
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));
// 把每個人的薪水提高5%
for (Employee e : staff)
e.raiseSalary(5);
// 打印所有Employee對象的信息
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
+ e.getHireDay());
}
}
Employee.java:
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;
}
}
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;
}
}
程序測試結果如下:
測試程序5:
編輯、編譯、調試運行程序5-12(教材189頁),結合運行結果理解程序;
掌握枚舉類的定義及用法;
在程序中相關代碼處添加新知識的註釋。
插入實例程序的代碼:
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)
{
Scanner 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);
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:編程練習1
定義抽象類Shape:
屬性:不可變常量double PI,值為3.14;
方法:public double getPerimeter();public double getArea())。
讓Rectangle與Circle繼承自Shape類。
編寫double sumAllArea方法輸出形狀數組中的面積和和double sumAllPerimeter方法輸出形狀數組中的周長和。
main方法中
1)輸入整型值n,然後建立n個不同的形狀。如果輸入rect,則再輸入長和寬。如果輸入cir,則再輸入半徑。
2) 然後輸出所有的形狀的周長之和,面積之和。並將所有的形狀信息以樣例的格式輸出。
3) 最後輸出每個形狀的類型與父類型,使用類似shape.getClass()(獲得類型),shape.getClass().getSuperclass()(獲得父類型);
思考sumAllArea和sumAllPerimeter方法放在哪個類中更合適?
輸入樣例:
3
rect
1 1
rect
2 2
cir
1
輸出樣例:
18.28
8.14
[Rectangle [width=1, length=1], Rectangle [width=2, length=2], Circle [radius=1]]
class Rectangle,class Shape
class Rectangle,class Shape
class Circle,class Shape
程序相關代碼:
shape:
package shape;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("個數");
int a = in.nextInt();
System.out.println("種類");
String rect="rect";
String cir="cir";
Shape[] num=new Shape[a];
for(int i=0;i<a;i++){
String input=in.next();
if(input.equals(rect)) {
System.out.println("長和寬");
int length = in.nextInt();
int width = in.nextInt();
num[i]=new Rectangle(width,length);
System.out.println("Rectangle["+"length:"+length+" width:"+width+"]");
}
if(input.equals(cir)) {
System.out.println("半徑");
int radius = in.nextInt();
num[i]=new Circle(radius);
System.out.println("Circle["+"radius:"+radius+"]");
}
}
Test c=new Test();
System.out.println("求和");
System.out.println(c.sumAllPerimeter(num));
System.out.println(c.sumAllArea(num));
for(Shape s:num) {
System.out.println(s.getClass()+","+s.getClass().getSuperclass());
}
}
public double sumAllArea(Shape score[])
{
double sum=0;
for(int i=0;i<score.length;i++)
sum+= score[i].getArea();
return sum;
}
public double sumAllPerimeter(Shape score[])
{
double sum=0;
for(int i=0;i<score.length;i++)
sum+= score[i].getPerimeter();
return sum;
}
}
Test:
package shape;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("個數");
int a = in.nextInt();
System.out.println("種類");
String rect="rect";
String cir="cir";
Shape[] num=new Shape[a];
for(int i=0;i<a;i++){
String input=in.next();
if(input.equals(rect)) {
System.out.println("長和寬");
int length = in.nextInt();
int width = in.nextInt();
num[i]=new Rectangle(width,length);
System.out.println("Rectangle["+"length:"+length+" width:"+width+"]");
}
if(input.equals(cir)) {
System.out.println("半徑");
int radius = in.nextInt();
num[i]=new Circle(radius);
System.out.println("Circle["+"radius:"+radius+"]");
}
}
Test c=new Test();
System.out.println("求和");
System.out.println(c.sumAllPerimeter(num));
System.out.println(c.sumAllArea(num));
for(Shape s:num) {
System.out.println(s.getClass()+","+s.getClass().getSuperclass());
}
}
public double sumAllArea(Shape score[])
{
double sum=0;
for(int i=0;i<score.length;i++)
sum+= score[i].getArea();
return sum;
}
public double sumAllPerimeter(Shape score[])
{
double sum=0;
for(int i=0;i<score.length;i++)
sum+= score[i].getPerimeter();
return sum;
}
}
實驗結果如下所示:
實驗3: 編程練習2
編制一個程序,將身份證號.txt 中的信息讀入到內存中,輸入一個身份證號或姓名,查詢顯示查詢對象的姓名、身份證號、年齡、性別和出生地。
插入程序代碼:
Main :
本周學習package id1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("D:/身份證號.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String number = linescanner.next();
String sex = linescanner.next();
String year = linescanner.next();
String province =linescanner.nextLine();
Student student = new Student();
student.setName(name);
student.setnumber(number);
student.setsex(sex);
student.setyear(year);
student.setprovince(province);
studentlist.add(student);
}
} catch (FileNotFoundException e) {
System.out.println("學生信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("學生信息文件讀取錯誤");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("1.按姓名查詢");
System.out.println("2.按身份證號查詢");
System.out.println("3.退出");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
System.out.println("請輸入姓名");
String studentname = scanner.next();
int nameint = findStudentByname(studentname);
if (nameint != -1) {
System.out.println("查找信息為:身份證號:"
+ studentlist.get(nameint).getnumber() + " 姓名:"
+ studentlist.get(nameint).getName() +" 性別:"
+studentlist.get(nameint).getsex() +" 年齡:"
+studentlist.get(nameint).getyaer()+" 地址:"
+studentlist.get(nameint).getprovince()
);
} else {
System.out.println("不存在該學生");
}
break;
case 2:
System.out.println("請輸入身份證號");
String studentid = scanner.next();
int idint = findStudentByid(studentid);
if (idint != -1) {
System.out.println("查找信息為:身份證號:"
+ studentlist.get(idint ).getnumber() + " 姓名:"
+ studentlist.get(idint ).getName() +" 性別:"
+studentlist.get(idint ).getsex() +" 年齡:"
+studentlist.get(idint ).getyaer()+" 地址:"
+studentlist.get(idint ).getprovince()
);
} else {
System.out.println("不存在該學生");
}
break;
case 3:
isTrue = false;
System.out.println("程序已退出!");
break;
default:
System.out.println("輸入有誤");
}
}
}
public static int findStudentByname(String name) {
int flag = -1;
int a[];
for (int i = 0; i < studentlist.size(); i++) {
if (studentlist.get(i).getName().equals(name)) {
flag= i;
}
}
return flag;
}
public static int findStudentByid(String id) {
int flag = -1;
for (int i = 0; i < studentlist.size(); i++) {
if (studentlist.get(i).getnumber().equals(id)) {
flag = i;
}
}
return flag;
}
Student:
public class Student {
private String name;
private String number ;
private String sex ;
private String year;
private String province;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getsex() {
return sex ;
}
public void setsex(String sex ) {
this.sex =sex ;
}
public String getyaer() {
return year;
}
public void setyear(String year ) {
this.year=year ;
}
public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
}
}
實驗結果如下所示:
實驗總結:
通過這一周的學習以及自己在後期的自學過程當中,我深入了解了什麽叫做繼承,以及在繼承中所包含的類型有哪些。繼承是用已有類來構建新類的一種機制,當定義了一個新類繼承了一個類時,這個新類繼承一個類時,這個新類就繼承了這個類的方法和域。而且繼承是具有層次的,其代碼也是可重用的,可以輕松定義子類。首先在學習過程當中我們學習了類,超類和子類的定義,讓我明白了父類和子類時相對的。還學習了泛型數組列表與對象包裝器與自動裝箱,在後面還介紹了反射的概念,它是在程序運行期間發現更多的類及其屬性的能力。並體會頗多,在今後的日子裏我會好好深入學習java知識。
201771010112羅松《面向對象程序設計(java)》第六周學習總結