201771010125王瑜《面向对象程序设计(Java)》第六周学习总结
???????????????????????????????????????????????????????????????????????????????????????????????????? 實驗六 繼承定義與使用
第一部分:理論知識
1.繼承
???? 繼承是用已有類來構建新類的一種機制。當定義了一個新類繼承了一個類時,這個新類就繼承了這個類的方法和域,同時在新類中添加新的方法和域以適應新的情況
?? 繼承是Java程序設計中的一項核心技術, 也是面向對象特征之一
?? 繼承的特點:a.具有層次結構
???????????????b.子類繼承了父類的域和方法
2.類、超類和子類
?? 類繼承的格式:class (新類名)+ extends (已有類名)
?? 已有類稱為:超類(superclass)、基類(base class)或父類(parent class)、基類(base class)
?? 新類稱作:子類(subclass)、派生類(derivedclass)或孩子類(child class)、派生類(derivedclass)或孩子類(child class)
3.super關鍵字
???? super是一個指示編譯器調用超類方法的特有關鍵字,它不是一個對象的引用,不能將super賦給另一個對象變量
???super關鍵字一般有兩個用途:一是調用超類的方法(格式:super.方法名()),二是調用超類的構造公式(:super())
4.繼承層次
??? 從一個超類擴展而來的類集合稱為繼承層次(inheritance hierarchy)。在繼承層次中,從某個類到其祖先的路徑被稱為該類的繼承鏈(inheritance chain),并且Java不支持多繼承
5.多態(tài)性
??? 多態(tài)性泛指在程序中同一個符號在不同的情況下具有不同解釋的現(xiàn)象
6.final類
??? 不允許繼承的類稱為 final類,在類的定義中用final修飾符加以說明
7.強制類型轉換
??? 如果要把一個超類對象賦給一個子類對象變量,就必須進行強制類型轉換。其格式為:子類對象=(子類)(超類對象)
8.Object:所有類的超類
? Object類是Java中所有類的祖先——每一個類都由它擴展而來。在不給出超類的情況下,Java會自動把Object作為要定義類的超類,可以使用類型為Object的變量指向任意類型的對象,但要對它們進行專門的操作都要進行類型轉換
9.訪問修飾符
??? a.public:該類或該類均可訪問
??? b.private:只有該類可以訪問
??? c.protected:該類及其子類的成員可以訪問,同一個包中的類也可以訪問
??? d.默認:相同包中的類可以訪問
10.枚舉類
??? 枚舉類是一個類,它的隱含超類是java.lang.Enum
??? 枚舉值并不是整數(shù)或其它類型,是被聲明的枚舉類的自身實例,例如A是Grade的一個實例
??? 枚舉類不能有public修飾的構造函數(shù),構造函數(shù)都是隱含private,編譯器自動處理
?
第二部分:實驗部分
?
1、實驗目的與要求
?
(1) 理解繼承的定義;
?
(2) 掌握子類的定義要求
?
(3) 掌握多態(tài)性的概念及用法;
?
(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; /** * 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]; // 用管理者和雇員對象填充數(shù)組 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()); } }
1 package inheritance; 2 3 import java.time.*; 4 5 public class Employee 6 { 7 private String name; 8 private double salary; 9 private LocalDate hireDay;//構建三個public對象// 10 11 public Employee(String name, double salary, int year, int month, int day) 12 { 13 this.name = name; 14 this.salary = salary; 15 hireDay = LocalDate.of(year, month, day); 16 } 17 18 public String getName() 19 { 20 return name; 21 } 22 23 public double getSalary() 24 { 25 return salary; 26 } 27 28 public LocalDate getHireDay() 29 { 30 return hireDay; 31 } 32 33 public void raiseSalary(double byPercent) 34 { 35 double raise = salary * byPercent / 100; 36 salary += raise; 37 } 38 } 1 package inheritance; 2 //關鍵字extends表示繼承,表明正在構造一個新類派生于一個已經(jīng)存在的類// 3 public class Manager extends Employee 4 { 5 private double bonus; 6 7 /** 8 * @param name the employee's name 9 * @param salary the salary 10 * @param year the hire year 11 * @param month the hire month 12 * @param day the hire day 13 */ 14 public Manager(String name, double salary, int year, int month, int day) 15 {//調用超類中含有的參數(shù)的構造器。// 16 super(name, salary, year, month, day); 17 bonus = 0; 18 } 19 20 public double getSalary() 21 {//子類要想訪問超類中的方法用關鍵字super// 22 double baseSalary = super.getSalary(); 23 return baseSalary + bonus; 24 } 25 26 public void setBonus(double b) 27 { 28 bonus = b; 29 } 30 }
?
理解并總結OO風格程序構造特點,理解Employee和Manager類的關系子類的用途
?
對于面向對象風格程序構造特點,大體有四個,即:抽象、封裝、繼承、多態(tài)。
?
繼承:簡單理解就是代碼復用,把重復使用的代碼精簡掉的一種手段。封裝:就是把一部分或全部屬性和部分功能(函數(shù))對外界屏蔽。多態(tài):沒有繼承就沒有多態(tài),繼承是多態(tài)的前提。雖然繼承自同一父類,但是相應的操作卻各不相同,這叫多態(tài)。
?
Employee和Manager使用extends關鍵字完成繼承關系。用父類進行聲明,子類進行構造。
?
測試程序2:
?
?? 編輯、編譯、調試運行教材PersonTest程序(教材163頁-165頁);
?
?? 掌握超類的定義及其使用要求;
?
?? 掌握利用超類擴展子類的要求;
?
?? 在程序中相關代碼處添加新知識的注釋。
?
1 package abstractClasses; 2 3 /** 4 * This program demonstrates abstract classes. 5 * @version 1.01 2004-02-21 6 * @author Cay Horstmann 7 */ 8 public class PersonTest//主類// 9 { 10 public static void main(String[] args) 11 { 12 Person[] people = new Person[2];?
//用Employee類和Student類填充people數(shù)組//?
13 14 // fill the people array with Student and Employee objects 15 people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1); 16 people[1] = new Student("Maria Morris", "computer science"); 1718 // print out names and descriptions of all Person objects
?
//打印出所有person類的名字和其他描述//?
19 for (Person p : people)20 System.out.println(p.getName() + ", " + p.getDescription()); 21 }
22 }
?
?
1 package abstractClasses; 2 3 public class Student extends Person//子類:student類繼承person類// 4 { 5 private String major;//創(chuàng)建一個私有屬性major// 6 7 /** 8 * @param nama the student's name 9 * @param major the student's major 10 */ 11 public Student(String name, String major) 12 { 13 // 將n傳遞給超類構造函數(shù)// 14 super(name);//子類直接調用超類中的name屬性// 15 this.major = major; 16 } 17 18 public String getDescription()//訪問器// 19 { 20 return "a student majoring in " + major; 21 } 22 }?
package abstractClasses;public abstract class Person//抽象類person// {public abstract String getDescription(); private String name;//創(chuàng)建一個私有屬性// public Person(String name)//構造器// { this.name = name; } public String getName()//訪問器// { return name; } }?
1 package abstractClasses; 2 3 import java.time.*; 4 5 public class Employee extends Person//子類:employee類繼承person類// 6 { 7 private double salary; 8 private LocalDate hireDay;//構建兩個私有屬性// 9 10 public Employee(String name, double salary, int year, int month, int day) 11 { 12 super(name);//子類不再重新定義,直接調用超類中的name// 13 this.salary = salary; 14 hireDay = LocalDate.of(year, month, day); 15 } 16 17 public double getSalary() 18 { 19 return salary; 20 } 21 22 public LocalDate getHireDay() 23 { 24 return hireDay; 25 } 26 27 public String getDescription() 28 { 29 return String.format("an employee with a salary of $%.2f", salary); 30 } 31 32 public void raiseSalary(double byPercent) 33 { 34 double raise = salary * byPercent / 100; 35 salary += raise; 36 }//定義兩個局部變量// 37 }?
?
測試程序3:
?
?? 編輯、編譯、調試運行教材程序5-8、5-9、5-10,結合程序運行結果理解程序(教材174頁-177頁);
?
?? 掌握Object類的定義及用法;
?
?? 在程序中相關代碼處添加新知識的注釋。
1 package equals; 2 3 /** 4 * This program demonstrates the equals method. 5 * @version 1.12 2012-01-26 6 * @author Cay Horstmann 7? */ 8 public class EqualsTest 9 { 10??? public static void main(String[] args) 11 ?? { 12?????? Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15); 13?????? Employee alice2 = alice1; 14?????? Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15); 15?????? Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1); 16 17?????? System.out.println("alice1 == alice2: " + (alice1 == alice2)); 18 19?????? System.out.println("alice1 == alice3: " + (alice1 == alice3)); 20 21?????? System.out.println("alice1.equals(alice3): " + alice1.equals(alice3)); 22 23?????? System.out.println("alice1.equals(bob): " + alice1.equals(bob)); 24 25?????? System.out.println("bob.toString(): " + bob); 26 27?????? Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15); 28?????? Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); 29?????? boss.setBonus(5000);//子類中賦初值為空,主類中用更改器更改為5000// 30?????? System.out.println("boss.toString(): " + boss); 31?????? System.out.println("carl.equals(boss): " + carl.equals(boss)); 32?????? System.out.println("alice1.hashCode(): " + alice1.hashCode()); 33?????? System.out.println("alice3.hashCode(): " + alice3.hashCode()); 34?????? System.out.println("bob.hashCode(): " + bob.hashCode()); 35?????? System.out.println("carl.hashCode(): " + carl.hashCode()); 36 ?? } 37 }
?
1 package equals; 2 3 public class Manager extends Employee//Manger類繼承employee類// 4 { 5 private double bonus;//創(chuàng)建私有屬性bonnus// 6 7 public Manager(String name, double salary, int year, int month, int day) 8 { 9 super(name, salary, year, month, day);//子類直接調用超類中已經(jīng)創(chuàng)建的屬性// 10 bonus = 0; 11 } 12 13 public double getSalary() 14 { 15 double baseSalary = super.getSalary(); 16 return baseSalary + bonus; 17 } 18 19 public void setBonus(double bonus) 20 { 21 this.bonus = bonus; 22 } 23 24 public boolean equals(Object otherObject)//測試是否是同一個超類// 25 { 26 if (!super.equals(otherObject)) return false; 27 Manager other = (Manager) otherObject; 28 // super.equals checked that this and other belong to the same class 29 return bonus == other.bonus; 30 } 31 32 public int hashCode()//重寫hashcode方法,讓相等的兩個對象獲取的hascode也相等// 33 { 34 return java.util.Objects.hash(super.hashCode(), bonus); 35 } 36 37 public String toString()//把其他類型的數(shù)據(jù)轉換為字符串類型的數(shù)據(jù)// 38 { 39 return super.toString() + "[bonus=" + bonus + "]"; 40 } 41 }?
1 package equals; 2 3 import java.time.*; 4 import java.util.Objects; 5 6 public class Employee 7 { 8 private String name; 9 private double salary; 10 private LocalDate hireDay;//創(chuàng)建三個私有屬性// 11 12 public Employee(String name, double salary, int year, int month, int day) 13 { 14 this.name = name; 15 this.salary = salary; 16 hireDay = LocalDate.of(year, month, day); 17 } 18 19 public String getName() 20 { 21 return name; 22 } 23 24 public double getSalary() 25 { 26 return salary; 27 } 28 29 public LocalDate getHireDay() 30 { 31 return hireDay; 32 } 33 34 public void raiseSalary(double byPercent) 35 { 36 double raise = salary * byPercent / 100; 37 salary += raise;//定義兩個局部變量// 38 } 39 40 public boolean equals(Object otherObject) 41 { 42 // 測試是否是同一個超類// 43 if (this == otherObject) return true; 44 45 // 顯示參數(shù)為空,返回faulse// 46 if (otherObject == null) return false; 47 48 // 類不匹配,則不相等// 49 if (getClass() != otherObject.getClass()) return false; 50 51 // 其他對象是非空employee類// 52 Employee other = (Employee) otherObject; 53 54 // 測試是否具有相同的值// 55 return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay); 56 } 57 58 public int hashCode() 59 { 60 return Objects.hash(name, salary, hireDay); 61 } 62 63 public String toString() 64 { 65 return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay 66 + "]"; 67 } 68 }?
?
測試程序4:
?
?? 在elipse IDE中調試運行程序5-11(教材182頁),結合程序運行結果理解程序;
?
?? 掌握ArrayList類的定義及用法;
?
?? 在程序中相關代碼處添加新知識的注釋。
?
1 package arrayList; 2 3 import java.time.*; 4 5 public class Employee 6 { 7 private String name; 8 private double salary; 9 private LocalDate hireDay; 10 11 public Employee(String name, double salary, int year, int month, int day) 12 { 13 this.name = name; 14 this.salary = salary; 15 hireDay = LocalDate.of(year, month, day); 16 } 17 18 public String getName() 19 { 20 return name; 21 } 22 23 public double getSalary() 24 { 25 return salary; 26 } 27 28 public LocalDate getHireDay() 29 { 30 return hireDay; 31 } 32 33 public void raiseSalary(double byPercent) 34 { 35 double raise = salary * byPercent / 100; 36 salary += raise; 37 }//定義兩個局部變量// 38 }?
?
?
測試程序5:
?
?? 編輯、編譯、調試運行程序5-12(教材189頁),結合運行結果理解程序;
?
?? 掌握枚舉類的定義及用法;
?
?? 在程序中相關代碼處添加新知識的注釋。
1 package enums; 2 3 import java.util.*; 4 5 /** 6 * This program demonstrates enumerated types. 7 * @version 1.0 2004-05-24 8 * @author Cay Horstmann 9 */ 10 public class EnumTest//主類// 11 { 12 public static void main(String[] args) 13 { 14 Scanner in = new Scanner(System.in); 15 System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) "); 16 String input = in.next().toUpperCase();//字符串轉換為大寫// 17 Size size = Enum.valueOf(Size.class, input); 18 System.out.println("size=" + size); 19 System.out.println("abbreviation=" + size.getAbbreviation()); 20 if (size == Size.EXTRA_LARGE) 21 System.out.println("Good job--you paid attention to the _."); 22 } 23 } 24 25 enum Size//枚舉類型(都是enum的子類)// 26 { 27 SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");//傳入?yún)?shù)// 28 29 private Size(String abbreviation) { this.abbreviation = abbreviation; } 30 public String getAbbreviation() { return abbreviation; } 31 32 private String abbreviation; 33 }?
實驗2:編程練習1
?
?? 定義抽象類Shape:
?
屬性:不可變常量double PI,值為3.14;
?
方法:public double getPerimeter();public double getArea())。
?
?? 讓Rectangle與Circle繼承自Shape類。
?
?? 編寫double sumAllArea方法輸出形狀數(shù)組中的面積和和double sumAllPerimeter方法輸出形狀數(shù)組中的周長和。
?
?? main方法中
?
1)輸入整型值n,然后建立n個不同的形狀。如果輸入rect,則再輸入長和寬。如果輸入cir,則再輸入半徑。 2) 然后輸出所有的形狀的周長之和,面積之和。并將所有的形狀信息以樣例的格式輸出。 3) 最后輸出每個形狀的類型與父類型,使用類似shape.getClass()(獲得類型),shape.getClass().getSuperclass()(獲得父類型);
?
思考sumAllArea和sumAllPerimeter方法放在哪個類中更合適?
?
輸入樣例:
?
1 3 2 3 rect 4 5 1 1 6 7 rect 8 9 2 2 10 11 cir 12 13 1?
輸出樣例:
?
18.288.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?
import java.util.Scanner;public class Work {public static void main(String[] args) { Scanner in = new Scanner(System.in); String rect = "rect"; String cir = "cir"; System.out.print("請輸入所需圖形的形狀個數(shù):"); int n = in.nextInt(); shape[] count = new shape[n]; for(int i=0;i<n;i++) { System.out.println("請輸入圖形形狀:"); String input = in.next(); if(input.equals(rect)) { double length = in.nextDouble(); double width = in.nextDouble(); System.out.println("長方形:"+"長:"+length+" 寬:"+width); count[i] = new Rect(length,width); } if(input.equals(cir)) { double radius = in.nextDouble(); System.out.println("圓:"+"半徑:"+radius); count[i] = new Cir(radius); } } Work c = new Work(); System.out.println(c.sumAllPerimeter(count)); System.out.println(c.sumAllArea(count)); for(shape s:count) { System.out.println(s.getClass()+", "+s.getClass().getSuperclass()); } }
?
public double sumAllArea(shape count[]){double sum = 0; for(int i = 0;i<count.length;i++) sum+= count[i].getArea(); return sum; } public double sumAllPerimeter(shape count[]) { double sum = 0; for(int i = 0;i<count.length;i++) sum+= count[i].getPerimeter(); return sum; } }?
1 public abstract class shape 2 { 3 double PI = 3.14; 4 public abstract double getPerimeter(); 5 public abstract double getArea(); 6 }?
public class Rect extends shape {private double width; private double length; public Rect(double w,double l) { this.width = w; this.length = l; } public double getPerimeter() { double Perimeter = 2*(length+width); return Perimeter; } public double getArea() { double Area = length*width; return Area; } }?
1 public class Cir extends shape 2 { 3 private double radius; 4 5 public Cir(double radius2) { 6 // TODO Auto-generated constructor stub 7 } 8 public double getPerimeter() 9 { 10 double Perimeter=2*PI*radius; 11 return Perimeter; 12 } 13 public double getArea() 14 { 15 double Area=PI*radius*radius; 16 return Area; 17 } 18 }?
結果
?
?
實驗3:編程練習2
?
編制一個程序,將身份證號.txt 中的信息讀入到內存中,輸入一個身份證號或姓名,查詢顯示查詢對象的姓名、身份證號、年齡、性別和出生地。
?
實驗代碼?1 import java.io.BufferedReader; ? 2 import java.io.File; ? 3 import java.io.FileInputStream; ? 4 import java.io.FileNotFoundException; ? 5 import java.io.IOException; ? 6 import java.io.InputStreamReader; ? 7 import java.util.ArrayList; ? 8 import java.util.Scanner; ? 9 10 public class Test{ 11???? private static ArrayList<Person> Personlist; 12???? public static void main(String[] args) { 13???????? Personlist = new ArrayList<>(); 14???????? Scanner scanner = new Scanner(System.in); 15???????? File file = new File("E:\\WPS Office\\身份證號.txt"); 16???????? try { 17???????????? FileInputStream fis = new FileInputStream(file); 18???????????? BufferedReader in = new BufferedReader(new InputStreamReader(fis)); 19???????????? String temp = null; 20???????????? while ((temp = in.readLine()) != null) { 21???????????????? 22 Scanner linescanner = new Scanner(temp); 23???????????????? 24???????????????? linescanner.useDelimiter(" ");??? 25???????????????? String name = linescanner.next(); 26???????????????? String ID = linescanner.next(); 27???????????????? String sex = linescanner.next(); 28???????????????? String age = linescanner.next(); 29???????????????? String birthplace =linescanner.nextLine(); 30???????????????? Person Person = new Person(); 31 ??????????????? Person.setname(name); 32 ??????????????? Person.setID(ID); 33 ??????????????? Person.setsex(sex); 34 ??????????????? Person.setage(age); 35 ??????????????? Person.setbirthplace(birthplace); 36 ??????????????? Personlist.add(Person); 37 38 ??????????? } 39???????? } catch (FileNotFoundException e) { 40???????????? System.out.println("查找不到信息"); 41 ??????????? e.printStackTrace(); 42???????? } catch (IOException e) { 43???????????? System.out.println("信息讀取有誤"); 44 ??????????? e.printStackTrace(); 45 ??????? } 46???????? boolean isTrue = true; 47???????? while (isTrue) { 48 49???????????? System.out.println("1.按姓名查找"); 50???????????? System.out.println("2.按身份證號查找"); 51???????????? System.out.println("3.退出"); 52???????????? int nextInt = scanner.nextInt(); 53???????????? switch (nextInt) { 54???????????? case 1: 55???????????????? System.out.println("請輸入姓名:"); 56???????????????? String Personname = scanner.next(); 57???????????????? int nameint = findPersonByname(Personname); 58???????????????? if (nameint != -1) { 59???????????????????? System.out.println("查找信息為:姓名:" 60???????????????????????????? + Personlist.get(nameint).getname() + "??? 身份證號:" 61???????????????????????????? + Personlist.get(nameint).getID() +"??? 年齡:" 62???????????????????????????? +Personlist.get(nameint).getage()?? +"??? 性別:" 63???????????????????????????? +Personlist.get(nameint).getsex()+"? 出生地:" 64???????????????????????????? +Personlist.get(nameint).getbirthplace() 65 ??????????????????????????? ); 66???????????????? } else { 67???????????????????? System.out.println("此人不存在!"); 68 ??????????????? } 69???????????????? break; 70???????????? case 2: 71???????????????? System.out.println("請輸入身份證號"); 72???????????????? String PersonID = scanner.next(); 73???????????????? int IDint = findPersonByID(PersonID); 74???????????????? if (IDint != -1) { 75???????????????????? System.out.println("查找信息為:姓名:" 76???????????????????????????? + Personlist.get(IDint).getname() + "
轉載于:https://www.cnblogs.com/wy-201771010125/p/9751043.html
總結
以上是生活随笔為你收集整理的201771010125王瑜《面向对象程序设计(Java)》第六周学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: mysql 数据表操作 存储引擎介绍
- 下一篇: 自动化运维工具 Ansible
