实验六 继承定义与使用
一 理论知识
1 继承:用已有类来构建新类的一种机制。当定义了一个新类继承了一个类时,这个新类就继承了这个类的方法和域,同时在新类中添加新的方法和域以适应新的情况。继承是Java程序设计中的一项核心技术,也是面向对象特征之一。
特点:具有层次结构,子类继承了父类的域和方法。
优点:代码可重用性,可以轻松定义子类,父类的域和方法可用于子类
2. 类、超类和子类:
类继承的格式:class新类名extends已有类名
已有类称为:超类(superclass)、基类(baseclass)或父类(parentclass)
–来自系统类库
–用户自定义类
新类称作:子类(subclass)、派生类(derivedclass)或孩子类(childclass)一般来说,子类比超类拥有的功能更加丰富。设计应用程序变得更加简单
3.多态性的概念:–多态性泛指在程序中同一个符号在不同的情况下具有不同解释的现象。
–超类中定义的域或方法,被子类继承之后,可以具有不同的数据类型或表现出不同的行为。
–这使得同一个域或方法在超类及其各个子类中具有不同的语义。
–超类中的方法在子类中可方法重。
4.final类:不允许继承的类称为final类,在类的定义中用final修饰符加以说明。类中的方法可定义为final的。这时子类就不能覆盖该方法。
如果一个类声明为final,属于它的方法会被自动设为final,但不包括域(如果域定义为final,在对象构造以
后,final域就不能再修改了)。
5.Object:所有类的超类Object类是Java中所有类的祖先——每一个类都由它扩展而来。在不给出超类的情况下,Java会自动把Object作为要定义类的超类。可以使用类型为Object的变量指向任意类型的对象。但
要对它们进行专门的操作都要进行类型转换。
6.tostring方法:Object类的toString方法返回一个代表该对象域值的字符串。toString方法返回字符串的格式:类名,然后在方括号中列举域值。通过getClass().getName()获得类名的字符串。toString的调用方式:
一个字符串与对象名通过操作符“+”连接起来,就会自动调用toString方法。Stringmessage=“Thecurrentemployeeis”+x;
如果x是任意一个对象,调用System.out.println(x),就会直接地调用x.toString(),并打印输出字符串。
定义子类的toString方法时,可先调用超类的toString方法super.toString()
toString方法是非常重要的调试工具。标准类库中,多数类
定义了toString方法,以便用户获得对象状态的必要信息。
二.实验
1、实验目的与要求
(1) 理解继承的定义;
(2) 掌握子类的定义要求
(3) 掌握多态性的概念及用法;
(4) 掌握抽象类的定义及用途;(做父类)
(5) 掌握类中4个成员访问权限修饰符的用途;
(6) 掌握抽象类的定义方法及用途;
(7)掌握Object类的用途及常用API;(java的顶层类,需要学习如何使用它的api)
(8) 掌握ArrayList类的定义方法及用法;
(9) 掌握枚举类定义方法及用途。
2、实验内容和步骤
实验1: 导入第5章示例程序,测试并进行代码注释。
测试程序1:
Ÿ 在elipse IDE中编辑、调试、运行程序5-1 (教材152页-153页) ;运行如下图所示
Ÿ 掌握子类的定义及用法;
Ÿ 结合程序运行结果,理解并总结OO风格程序构造特点,理解Employee和Manager类的关系子类的用途,并在代码中添加注释。
1 package inheritance; 2 3 /** 4 * This program demonstrates inheritance. 5 * @version 1.21 2004-02-21 6 * @author Cay Horstmann 7 */ 8 public class ManagerTest 9 { 10 public static void main(String[] args) 11 { 12 //建立一个 Manager object 13 Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); 14 boss.setBonus(5000); 15 16 Employee[] staff = new Employee[3]; 17 18 // 使用Manager和Employee对象填充staff数组 19 20 staff[0] = boss;//boss是Employee对象的子类(说明父类对象变量可以引用子类) 21 staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); 22 staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15); 23 24 //输出所有雇员信息 25 for (Employee e : staff) 26 System.out.println("name=" + e.getName() + ",salary=" + e.getSalary()); 27 } 28 }
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;//属性 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 3 public class Manager extends Employee//子类为Manager,父类为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 { 16 super(name, salary, year, month, day);//表明调用父类的构造器 17 bonus = 0; 18 }//子类构造器 19 20 public double getSalary() 21 { 22 double baseSalary = super.getSalary();//调用父类的getsalary方法 23 return baseSalary + bonus; 24 }//访问器 25 26 public void setBonus(double b) 27 { 28 bonus = b; 29 }//更改器(根据获得津贴的值更改) 30 }
测试程序2:
Ÿ 编辑、编译、调试运行教材PersonTest程序(教材163页-165页);
Ÿ 掌握超类的定义及其使用要求;
Ÿ 掌握利用超类扩展子类的要求;
Ÿ 在程序中相关代码处添加新知识的注释。
1 package abstractClasses; 2 3 public class Student extends Person //子类为student,父类为person 4 { 5 private String 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传递到 superclass constructor 14 super(name); //表明调用父类的构造器 15 this.major = major; 16 } // 子类构造器 17 18 public String getDescription() 19 { 20 return "a student majoring in " + major; 21 } 22 } //访问器
1 package abstractClasses; 2 3 public abstract class Person //父类 4 { 5 public abstract String getDescription(); 6 private String name; //属性 7 8 public Person(String name) 9 { 10 this.name = name; 11 } //构造器 12 13 public String getName() 14 { 15 return name; 16 } //访问器 17 }
1 package abstractClasses; 2 3 import java.time.*; 4 5 public class Employee extends Person //子类为emploee,父类为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); //表明调用父类的构造器 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 }
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]; 13 14 // 用学生和雇员的对象填充人组 15 people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1); // 将子类对象赋给父类对象 16 people[1] = new Student("Maria Morris", "computer science"); //将子类对象赋给父类变量 17 18 // 输出所有个人对象的名称和描述 19 for (Person p : people) 20 System.out.println(p.getName() + ", " + p.getDescription()); //输出 21 } 22 }
测试程序3:
Ÿ 编辑、编译、调试运行教材程序5-8、5-9、5-10,结合程序运行结果理解程序(教材174页-177页);
Ÿ 掌握Object类的定义及用法;
Ÿ 在程序中相关代码处添加新知识的注释。
ackage 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; // must return false if the explicit parameter is null if (otherObject == null) return false; // 如果显式参数为空,则必须返回假 if (getClass() != otherObject.getClass()) return false; // 现在我们知道其他对象是一个非空员工 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 + "]"; } //返回字符串 }
package equals; public class Manager extends Employee //子类为manager,父类为emploee { 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 + "]"; } }
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); 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 }
测试程序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)); // 把每个人的工资上涨百分之五
for (Employee e : staff) e.raiseSalary(5); // 输出所有的雇员信息 for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } }
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) ");//输出显示enter a size 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 //为枚举类增加构造函数 26 { 27 SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL"); 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方法输出形状数组中的面积和和double sumAllPerimeter方法输出形状数组中的周长和。
Ÿ main方法中
1)输入整型值n,然后建立n个不同的形状。如果输入rect,则再输入长和宽。如果输入cir,则再输入半径。
2) 然后输出所有的形状的周长之和,面积之和。并将所有的形状信息以样例的格式输出。
3) 最后输出每个形状的类型与父类型,使用类似shape.getClass()(获得类型),shape.getClass().getSuperclass()(获得父类型);
1 package shape; 2 3 import java.util.*; 4 5 public class ShapeTest { 6 public static void main(String[] args) { 7 Scanner in=new Scanner(System.in); 8 9 System.out.println("n的值为:"); 10 int n=in.nextInt(); 11 String Rectangle = "rect"; 12 String Circle = "cir"; 13 shape[] staff = new shape[n]; 14 for(int i=0;i<n;i++) { 15 //System.out.println("图形形状为:"); 16 String input = in.next(); 17 if(input.equals("rect")) { 18 //System.out.print("长方形的长和宽为:"); 19 double width = in.nextDouble(); 20 double length = in.nextDouble(); 21 System.out.println("Rectangle ["+"length="+length+" width="+width+"]"); 22 staff[i] = new Rectangle(width,length); 23 } 24 if(input.equals("cir")) { 25 //System.out.print("圆形半径为:"); 26 double radius = in.nextDouble(); 27 System.out.println("Circle ["+"radius="+radius+"]"); 28 staff[i] = new Circle(radius); 29 } 30 } 31 ShapeTest rescult = new ShapeTest(); 32 System.out.println(rescult.sumAllPerimeter(staff)); 33 System.out.println(rescult.sumAllArea(staff)); 34 } 35 public double sumAllPerimeter(shape staff[]) { 36 double sum = 0; 37 for(int i = 0;i<staff.length;i++) 38 sum+= staff[i].getPerimeter(); 39 return sum; 40 } 41 public double sumAllArea(shape staff[]) { 42 double sum = 0; 43 for(int i = 0;i<staff.length;i++) 44 sum += staff[i].getArea(); 45 return sum; 46 } 47 }
1 package shape; 2 3 public abstract class shape { 4 public abstract double getPerimeter(); 5 public abstract double getArea(); 6 double PI = 3.14; 7 }
1 package shape; 2 3 public class Rectangle extends shape{ 4 private double width; 5 private double length; 6 public Rectangle(double x,double y) { 7 this.width = x; 8 this.length = y; 9 } 10 public double getPerimeter() { 11 double Perimeter = (width+length)*2; 12 return Perimeter; 13 } 14 public double getArea() { 15 double Area = width*length; 16 return Area; 17 } 18 }
1 package shape; 2 3 public class Circle extends shape{ 4 private double radius; 5 public Circle(double r) { 6 this.radius = r; 7 } 8 public double getPerimeter() { 9 double Perimeter = 2*PI*radius; 10 return Perimeter; 11 } 12 public double getArea() { 13 double Area = radius*radius*PI; 14 return Area; 15 } 16 }
思考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
实验3: 编程练习2
编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。
1 package idcard; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileNotFoundException; 7 import java.io.IOException; 8 import java.io.InputStreamReader; 9 import java.util.ArrayList; 10 import java.util.Scanner; 11 12 public class ddd{ 13 private static ArrayList<cccccc> studentlist; 14 public static void main(String[] args) { 15 studentlist = new ArrayList<>(); 16 Scanner scanner = new Scanner(System.in); 17 File file = new File("E:/身份证号.txt"); 18 try { 19 FileInputStream fis = new FileInputStream(file); 20 BufferedReader in = new BufferedReader(new InputStreamReader(fis)); 21 String temp = null; 22 while ((temp = in.readLine()) != null) { 23 24 Scanner linescanner = new Scanner(temp); 25 linescanner.useDelimiter(" "); 26 String name = linescanner.next(); 27 String number = linescanner.next(); 28 String sex = linescanner.next(); 29 String age = linescanner.next(); 30 String province =linescanner.nextLine(); 31 cccccc student = new cccccc(); 32 student.setName(name); 33 student.setnumber(number); 34 student.setsex(sex); 35 student.setage(age); 36 student.setprovince(province); 37 studentlist.add(student); 38 39 } 40 } catch (FileNotFoundException e) { 41 System.out.println("学生信息文件找不到"); 42 e.printStackTrace(); 43 } catch (IOException e) { 44 System.out.println("学生信息文件读取错误"); 45 e.printStackTrace(); 46 } 47 boolean isTrue = true; 48 while (isTrue) { 49 50 System.out.println("1.按姓名查询"); 51 System.out.println("2.按身份证号查询"); 52 System.out.println("3.退出"); 53 int nextInt = scanner.nextInt(); 54 switch (nextInt) { 55 case 1: 56 System.out.println("请输入姓名"); 57 String studentname = scanner.next(); 58 int nameint = findStudentByname(studentname); 59 if (nameint != -1) { 60 System.out.println("身份证号:" 61 + studentlist.get(nameint).getnumber() + " 姓名:" 62 + studentlist.get(nameint).getName() +" 性别:" 63 +studentlist.get(nameint).getsex() +" 年龄:" 64 +studentlist.get(nameint).getage()+" 地址:" 65 +studentlist.get(nameint).getprovince() 66 ); 67 } else { 68 System.out.println("不存在该学生"); 69 } 70 break; 71 case 2: 72 System.out.println("请输入身份证号"); 73 String studentid = scanner.next(); 74 int idint = findStudentByid(studentid); 75 if (idint != -1) { 76 System.out.println("身份证号:" 77 + studentlist.get(idint ).getnumber() + " 姓名:" 78 + studentlist.get(idint ).getName() +" 性别:" 79 +studentlist.get(idint ).getsex() +" 年龄:" 80 +studentlist.get(idint ).getage()+" 地址:" 81 +studentlist.get(idint ).getprovince() 82 ); 83 } else { 84 System.out.println("不存在该学生"); 85 } 86 break; 87 case 3: 88 isTrue = false; 89 System.out.println("感谢使用"); 90 break; 91 default: 92 System.out.println("输入有误"); 93 } 94 } 95 } 96 97 98 public static int findStudentByname(String name) { 99 int flag = -1; 100 int a[]; 101 for (int i = 0; i < studentlist.size(); i++) { 102 if (studentlist.get(i).getName().equals(name)) { 103 flag= i; 104 } 105 } 106 return flag; 107 108 } 109 110 111 public static int findStudentByid(String id) { 112 int flag = -1; 113 114 for (int i = 0; i < studentlist.size(); i++) { 115 if (studentlist.get(i).getnumber().equals(id)) { 116 flag = i; 117 } 118 } 119 return flag; 120 121 } 122 123 124 }
package idcard; public class cccccc { private String name; private String number ; private String sex ; private String age; 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 getage() { return age; } public void setage(String age ) { this.age=age ; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } }
1 package idcard; 2 3 public class cccccc { 4 5 private String name; 6 private String number ; 7 private String sex ; 8 private String age; 9 private String province; 10 11 12 public String getName() { 13 return name; 14 } 15 public void setName(String name) { 16 this.name = name; 17 } 18 public String getnumber() { 19 return number; 20 } 21 public void setnumber(String number) { 22 this.number = number; 23 } 24 public String getsex() { 25 return sex ; 26 } 27 public void setsex(String sex ) { 28 this.sex =sex ; 29 } 30 public String getage() { 31 return age; 32 } 33 public void setage(String age ) { 34 this.age=age ; 35 } 36 public String getprovince() { 37 return province; 38 } 39 public void setprovince(String province) { 40 this.province=province ; 41 } 42 43 44 }
三.实验总结:理解继承的定义;
掌握了父类,子类的定义要求 掌握多态性的概念及用法; 掌握抽象类的定义及用途;(做父类)掌握类中4个成员访问权限修饰符的用途;掌握抽象类的定义方法及用途;
掌握Object类的用途及常用API;(java的顶层类,需要学习如何使用它的api)掌握ArrayList类的定义方法及用法; 掌握枚举类定义方法及用途。编程能力有所提高,还需急促努力