201771010106東文財《面向對象程序設計(java)》 實驗6
實驗六繼承定義與使用
實驗時間 2018-9-28
一.知識總結
1、繼承的概述:在多個類中存在相同的屬性和行為,把這些相同的部分抽取到一個單獨的類中,把這個單獨的類叫作父類,也叫基類或者超類,把其他被抽取的類叫作子類,並且父類的所有屬性和方法(除private修飾的私有屬性和方法外),子類都可以調用。這樣的一種行為就叫做繼承。(相同的東西在父類,不同的東西在子類)
2、繼承的關鍵字:extends
3、繼承的格式:class 子類名 extends 父類名{ }
4、在代碼中使用繼承提高了代碼的復用性和維護性,讓類與類直接產生了關系。
5、繼承的註意點:
①子類只能繼承父類所有的非私有的成員方法和成員變量,private修飾的不能繼承。
②子類不能繼承父類的構造方法,但可以通過 super 關鍵字去訪問父類的構造方法。(先初始化父類,再執行自己)
③不同包不能繼承。
6、在使用 super 的時候,我們還需要了解關鍵字 super 和 this 的區別:
super :到父類中去找方法,沒有引用的作用;也可以用於其他方法中;與this調用構造方的重載一樣,用於第一行。
this:是指當前正在初始化的這個對象的引用。
二.實驗部分:
1、實驗目的與要求
(1) 理解繼承的定義;
(2) 掌握子類的定義要求
(3) 掌握多態性的概念及用法;
(4) 掌握抽象類的定義及用途;
(5) 掌握類中4個成員訪問權限修飾符的用途;
(6) 掌握抽象類的定義方法及用途;
(7)掌握Object類的用途及常用API;
(8) 掌握ArrayList類的定義方法及用法;
(9) 掌握枚舉類定義方法及用途。
2、實驗內容和步驟
實驗1: 導入第5章示例程序,測試並進行代碼註釋。
測試程序1:
? 在elipse IDE中編輯、調試、運行程序5-1 (教材152頁-153頁) ;
? 掌握子類的定義及用法;
? 結合程序運行結果,理解並總結OO風格程序構造特點,理解Employee和Manager類的關系子類的用途,並在代碼中添加註釋。
package inheritance;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 inheritance; public class Manager extends Employee
//關鍵字extends表示繼承。表明正在構造一個新類派生於一個已經存在的類。已經存在的類稱為超類/基類/或者父類;新類稱為子類/派生類/或者孩子類。 { private double bonus; /** * @param name the employee‘s name * @param salary the salary * @param year the hire year * @param month the hire month * @param day the hire day */ public Manager(String name, double salary, int year, int month, int day) { super(name, salary, year, month, day);
//調用超類中含有n,s,year,month,day參數的構造器 bonus = 0; } public double getSalary()
//子類要想訪問要想訪問超類中的方法需要使用特定的關鍵字super, { double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b) { bonus = b; } }
package inheritance; /** * This program demonstrates inheritance. * @version 1.21 2004-02-21 * @author Cay Horstmann */ public class ManagerTest { public static void main(String[] args) { // 構建管理者對象 Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); boss.setBonus(5000); Employee[] staff = new Employee[3]; // 用管理者和雇員對象填充工作人員數組 staff[0] = boss; staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15); // 打印所有員工對象的信息 for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary()); } }
實驗結果:
測試程序2:
? 編輯、編譯、調試運行教材PersonTest程序(教材163頁-165頁);
? 掌握超類的定義及其使用要求;
? 掌握利用超類擴展子類的要求;
? 在程序中相關代碼處添加新知識的註釋。
package abstractClasses; import java.time.*; public class Employee extends Person { private double salary; private LocalDate hireDay; public Employee(String name, double salary, int year, int month, int day) { super(name); this.salary = salary; hireDay = LocalDate.of(year, month, day); } public double getSalary() { return salary; } public LocalDate getHireDay() { return hireDay; } //重寫父類方法,返回一個格式化的字符串 public String getDescription() { return String.format("an employee with a salary of $%.2f", salary); } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } }
package abstractClasses; public abstract class Person {
//包含一個或多個抽象方法的類被稱為抽象類,由abstract關鍵字修飾 public abstract String getDescription(); private String name; public Person(String name) { this.name = name; } public String getName() { return name; } }
package abstractClasses; /** * This program demonstrates abstract classes. * @version 1.01 2004-02-21 * @author Cay Horstmann */ public class PersonTest { public static void main(String[] args) {
//抽象類的聲明,但不能將抽象類實例化 ,實例化的是Person類的子類 Person[] people = new Person[2]; // 用學生和雇員填充人物數組
people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1); people[1] = new Student("Maria Morris", "computer science"); // 打印所有人對象的名稱和描述 for (Person p : people) System.out.println(p.getName() + ", " + p.getDescription()); } }
package abstractClasses; public class Student extends Person { private String major; /** * @param nama the student‘s name * @param major the student‘s major */ public Student(String name, String major) { // 通過n to 總綱構造函數 super(name); this.major = major; } public String getDescription() { return "a student majoring in " + major; } }
實驗結果:
測試程序3:
? 編輯、編譯、調試運行教材程序5-8、5-9、5-10,結合程序運行結果理解程序(教材174頁-177頁);
? 掌握Object類的定義及用法;
? 在程序中相關代碼處添加新知識的註釋。
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語句判斷兩個引用是否是同一個,如果是那麽這兩個對象肯定相等 if (this == otherObject) return true; // 如果顯式參數為空,則必須返回false if (otherObject == null) return false; // if the classes don‘t match, they can‘t be equal if (getClass() != otherObject.getClass()) return false; // 現在我們知道另一個對象是非空雇員 Employee 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()// toString()方法 { return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; } }
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; public class Manager extends 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; // 檢查這個和其他屬於同一個類 return bonus == other.bonus; } public int hashCode() { return java.util.Objects.hash(super.hashCode(), bonus); } public String toString() { return super.toString() + "[bonus=" + bonus + "]"; } }
實驗結果:
測試程序4:
? 在elipse IDE中調試運行程序5-11(教材182頁),結合程序運行結果理解程序;
? 掌握ArrayList類的定義及用法;
? 在程序中相關代碼處添加新知識的註釋。
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) { // 用三個雇員對象填充工作人員數組列表
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); // 打印所有員工對象的信息 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; } }
實驗結果:
測試程序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 { private static Scanner in; public static void main(String[] args) { 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
package shape; import java.math.*; import java.util.*; import shape.shape; import shape.Rectangle; import shape.Circle; public class shapecount { public static void main(String[] args) { Scanner in = new Scanner(System.in); String rect = "rect"; String cir = "cir"; System.out.print("請輸入形狀個數:"); int n = in.nextInt(); shape[] score = new shape[n]; for(int i=0;i<n;i++) { System.out.println("請輸入形狀類型 (rect or cir):"); String input = in.next(); if(input.equals(rect)) { double length = in.nextDouble(); double width = in.nextDouble(); System.out.println("Rectangle["+"length:"+length+" width:"+width+"]"); score[i] = new Rectangle(width,length); } if(input.equals(cir)) { double radius = in.nextDouble(); System.out.println("Circle["+"radius:"+radius+"]"); score[i] = new Circle(radius); } } shapecount c = new shapecount(); System.out.println(c.sumAllPerimeter(score)); System.out.println(c.sumAllArea(score)); for(shape s:score) { 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; } }
package shape; public class Rectangle extends shape { private double width; private double length; public Rectangle(double w,double l) { this.width = w; this.length = l; } public double getPerimeter() { double Perimeter = (width+length)*2; return Perimeter; } public double getArea() { double Area = width*length; return Area; } public String toString() { return getClass().getName() + "[ width=" + width + "]"+ "[length=" + length + "]"; } }
package shape; public abstract class shape { double PI = 3.14; public abstract double getPerimeter(); public abstract double getArea(); }
package shape; public class Circle extends shape { private double radius; public Circle(double r) { radius = r; } public double getPerimeter() { double Perimeter = 2*PI*radius; return Perimeter; } public double getArea() { double Area = PI*radius*radius; return Area; } public String toString() { return getClass().getName() + "[radius=" + radius + "]"; } }
實驗結果:
實驗3:編程練習2
編制一個程序,將身份證號.txt 中的信息讀入到內存中,輸入一個身份證號或姓名,查詢顯示查詢對象的姓名、身份證號、年齡、性別和出生地。
package qq; 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 Test{ private static ArrayList<Citizen> citizenlist; public static void main(String[] args) { citizenlist = 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 id = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String address =linescanner.nextLine(); Citizen citizen = new Citizen(); citizen.setName(name); citizen.setId(id); citizen.setSex(sex); citizen.setAge(age); citizen.setAddress(address); citizenlist.add(citizen); } } 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 citizenname = scanner.next(); int nameint = findCitizenByname(citizenname); if (nameint != -1) { System.out.println("查找信息為:身份證號:" + citizenlist.get(nameint).getId() + " 姓名:" + citizenlist.get(nameint).getName() +" 性別:" +citizenlist.get(nameint).getSex() +" 年齡:" +citizenlist.get(nameint).getAge()+" 地址:" +citizenlist.get(nameint).getAddress() ); } else { System.out.println("不存在該公民"); } break; case 2: System.out.println("請輸入身份證號"); String citizenid = scanner.next(); int idint = findCitizenByid(citizenid); if (idint != -1) { System.out.println("查找信息為:身份證號:" + citizenlist.get(idint ).getId() + " 姓名:" + citizenlist.get(idint ).getName() +" 性別:" +citizenlist.get(idint ).getSex() +" 年齡:" +citizenlist.get(idint ).getAge()+" 地址:" +citizenlist.get(idint ).getAddress() ); } else { System.out.println("不存在該公民"); } break; case 3: isTrue = false; System.out.println("程序已退出!"); break; default: System.out.println("輸入有誤"); } } } public static int findCitizenByname(String name) { int flag = -1; int a[]; for (int i = 0; i < citizenlist.size(); i++) { if (citizenlist.get(i).getName().equals(name)) { flag= i; } } return flag; } public static int findCitizenByid(String id) { int flag = -1; for (int i = 0; i < citizenlist.size(); i++) { if (citizenlist.get(i).getId().equals(id)) { flag = i; } } return flag; } }
package qq; public class Citizen { private String name; private String id ; private String sex ; private String age; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSex() { return sex ; } public void setSex(String sex ) { this.sex =sex ; } public String getAge() { return age; } public void setAge(String age ) { this.age=age ; } public String getAddress() { return address; } public void setAddress(String address) { this.address=address ; } }
實驗結果:
實驗總結:
上周我們學習了第五章,這章中主要學了繼承這一概念,通過繼承人們可以在已存在的類構造一個新類,繼承已存在的類就是復用這些類的方法和域,通過繼承這一概念我們學習了一些類的概念如:超類,基類(父類),子類等。總的來說本章的知識點也是比較重要的,不過我對本章的知識掌握的不是很好,我會繼續努力的,多多敲代碼。
201771010106東文財《面向對象程序設計(java)》 實驗6