实验六 继承定义与使用
实验时间 2018-9-28
1、实验目的与要求
(1) 理解继承的定义;
继承就是用已有类来构建新类的一种机制,当你继承了一个类时,就继承了这个类的方法和字段,同时你也可以在新类中添加新的方法和变量以适应新的情况。
继承的本质是代码复用。
(2) 掌握子类的定义要求
子类和超类是“is-a”关系。一般来说,子类比超类拥有的功能更加丰富。使用父类类型的引用指向子类的对象; 该引用只能调用父类中定义的方法和变量; 如果子类中重写了父类中的一个方法,那么在调用这个方法的时候,将会调用子类中的这个方法;(动态连接、动态调用) 变量不能被重写(覆盖),”重写“的概念只针对方法,如果在子类中”重写“了父类中的变量,那么在编译时会报错。
(3) 掌握多态性的概念及用法;
多态性:发送消息给某个对象,让该对象自行决定响应何种行为。 通过将子类对象引用赋值给超类对象引用变量来实现动态方法调用。 java 的这种机制遵循一个原则:当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法。
(4) 掌握抽象类的定义及用途;如果自下而上仰视类的继承层次结构,位于上层的类更具通用性,甚至可能更加抽象。从某种角度看,祖先类更加通用,人们只将它作为派生其他类的基类,而不想作为使用的特定的实例类。为了提高程序的清晰度,包含一个或多个抽象方法的类本身必须被声明为抽象的。除了抽象方法之外,抽象类还可以包含具体数据和具体方法。 抽象方法充当着占位的角色,它们的具体实现在子类中。扩展抽象类可以有两种选择:一种是在子类中实现部分抽象方法,这样就必须将子类也标记为抽象类;另一种是实现全部抽象方法,这样子类就可以不是抽象的了。此外,类即使不含抽象方法,也可以将类声明为抽象类。 抽象类不能被实例化,即不能创建对象,只能产生子类。可以创建抽象类的对象变量,只是这个变量必须指向它的非抽象子类的对象。
(5) 掌握类中4个成员访问权限修饰符的用途
private--私有域或私有方法:只能在定义它的类中使用
public--公有域或公有方法:在任何其他的类中都可以访问
protected--受保护的域或方法:在所有子类和本包中可以访问
不用修饰符--友好域和友好方法:在同一包中的不同类之间访问
(7)掌握Object类的用途及常用API;
Object类是Java中所有类最终的祖先——每一个类都由它扩展而来。也就是说,在不给出超类的情况下,Java会自动把Object作为要定义类的超类。 可以使用类型为Object的变量指向任意类型的对象。但要对他们进行专门的操作,都要进行类型转换。
(8) 掌握ArrayList类的定义方法及用法;
ArrayList提供了三个构造器: public ArrayList(); 默认的构造器,将会以默认(16)的大小来初始化内部的数组
(9) 掌握枚举类定义方法及用途。
2、实验内容和步骤
实验1: 导入第5章示例程序,测试并进行代码注释。
测试程序1:
Ÿ 在elipse IDE中编辑、调试、运行程序5-1 (教材152页-153页) ;
Ÿ 掌握子类的定义及用法;
Ÿ 结合程序运行结果,理解并总结OO风格程序构造特点,理解Employee和Manager类的关系子类的用途,并在代码中添加注释。
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类{ 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)//定义Manager方法 15 { 16 super(name, salary, year, month, day); 17 bonus = 0; 18 } 19 20 public double getSalary()//添加计算工资的方法 21 { 22 double baseSalary = super.getSalary(); 23 return baseSalary + bonus; 24 } 25 26 public void setBonus(double b) 27 { 28 bonus = b; 29 } 30 }
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对象 13 Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15)//引用数组创建Manager的信息 14 boss.setBonus(5000); 15 16 Employee[] staff = new Employee[3]; 17 18 // 将经理和雇员都填充到数组中 19 20 staff[0] = boss; 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 }
测试程序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]; 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 }
1 package abstractClasses;
2
3 public class Student extends 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 // 创建一个超类 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 import java.time.*; 4 5 public class Employee extends 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 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 }
测试程序3:
Ÿ 编辑、编译、调试运行教材程序5-8、5-9、5-10,结合程序运行结果理解程序(教材174页-177页);
Ÿ 掌握Object类的定义及用法;
Ÿ 在程序中相关代码处添加新知识的注释。
1 package arrayList;
2
3 import java.util.*; 4 5 /** 6 * This program demonstrates the ArrayList class. 7 * @version 1.11 2012-01-26 8 * @author Cay Horstmann 9 */ 10 public class ArrayListTest 11 { 12 public static void main(String[] args) 13 { 14 // 填充雇员数组信息
15 ArrayList<Employee> staff = new ArrayList<>(); 16 17 staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15)); 18 staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1)); 19 staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15)); 20 21 // 用以下方法为雇员涨5%的薪资 22 for (Employee e : staff) 23 e.raiseSalary(5); 24 25 // 输出所有雇员对象的信息
26 for (Employee e : staff) 27 System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" 28 + e.getHireDay()); 29 } 30 }
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 }
测试程序4:
Ÿ 在elipse IDE中调试运行程序5-11(教材182页),结合程序运行结果理解程序;
Ÿ 掌握ArrayList类的定义及用法;
Ÿ 在程序中相关代码处添加新知识的注释。
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//声明一个尺寸的枚举类型 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 }
测试程序5:
Ÿ 编辑、编译、调试运行程序5-12(教材189页),结合运行结果理解程序;
Ÿ 掌握枚举类的定义及用法;
Ÿ 在程序中相关代码处添加新知识的注释。
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; 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 // 若不相等则返回错误,或返回空 46 if (otherObject == null) return false; 47 48 // 如果不是相同类型则不相等,返回错误信息 49 if (getClass() != otherObject.getClass()) return false; 50 51 // 确定other中的对象是雇员对象 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 }
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 //添加Manager的信息 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 } 37 }
1 package equals;
2
3 public class Manager extends Employee//Manager类继承Employee类 4 { 5 private double bonus; 6 7 public Manager(String name, double salary, int year, int month, int day) 8 { 9 super(name, salary, year, month, day); 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 // 检查超类是否与此类相等 29 return bonus == other.bonus; 30 } 31 32 public int hashCode() 33 { 34 return java.util.Objects.hash(super.hashCode(), bonus); 35 } 36 37 public String toString() 38 { 39 return super.toString() + "[bonus=" + bonus + "]"; 40 } 41 }
实验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
1 import java.util.Scanner;
2 public class calculate
3 {
4 public static void main(String[] args)
5 {
6 int r;
7 int x;
8 int y;
9 int i;
10 int a=100;
11 Scanner num;
12 num = new Scanner(System.in);
13 System.out.println("Input the num");
14 i = num.nextInt();
15 for(i=0;i<a;i++)
16 {
17 Scanner kind;
18 kind = new Scanner(System.in);
19 System.out.println("Input the shape");
20 String rect="rect";
21 String cir="cir";
22 String input=kind.next();
23 if(input.equals(rect))
24 {
25 Scanner sc;
26 sc = new Scanner(System.in);
27 System.out.println("Input the Rectangle length:");
28 x = sc.nextInt();
29 System.out.println("Input the Rectangle width:");
30 y = sc.nextInt();
31 System.out.println("Rectangle:"+"\n\n" +"\t"+"Perimeter:"+rectangle.getPerimeter(x,y)+"\n\n"+"\t"+"Area:"+rectangle.getArea(x,y)+"\n");
32 }
33 if(input.equals(cir))
34 {
35 Scanner sc;
36 sc = new Scanner(System.in);
37 System.out.println("Input the Circle radius:");
38 r = sc.nextInt();
39 System.out.println("Circlr:"+"\n\n"+"\t"+"Perimeter:"+circle.getPerimeter(r)+"\n\n"+"\t"+"Area"+circle.getArea(r)+"\n");
40 }
41 }
42 }
43 }
import java.util.Scanner;
public class calculate
{
public static void main(String[] args)
{
int r;
int x;
int y;
int i;
int a=100;
Scanner num;
num = new Scanner(System.in);
System.out.println("Input the num");
i = num.nextInt();
for(i=0;i<a;i++)
{
Scanner kind;
kind = new Scanner(System.in);
System.out.println("Input the shape");
String rect="rect";
String cir="cir";
String input=kind.next();
if(input.equals(rect))
{
Scanner sc;
sc = new Scanner(System.in);
System.out.println("Input the Rectangle length:");
x = sc.nextInt();
System.out.println("Input the Rectangle width:");
y = sc.nextInt();
System.out.println("Rectangle:"+"\n\n" +"\t"+"Perimeter:"+rectangle.getPerimeter(x,y)+"\n\n"+"\t"+"Area:"+rectangle.getArea(x,y)+"\n");
}
if(input.equals(cir))
{
Scanner sc;
sc = new Scanner(System.in);
System.out.println("Input the Circle radius:");
r = sc.nextInt();
System.out.println("Circlr:"+"\n\n"+"\t"+"Perimeter:"+circle.getPerimeter(r)+"\n\n"+"\t"+"Area"+circle.getArea(r)+"\n");
}
}
}
}
1 class rectangle extends shape
2 {//子类继承父类 3 public static double getArea(double width, double height) 4 { 5 return width*height; 6 } 7 8 9 public static double getPerimeter(double width, double height) 10 { 11 return 2*(width+height); 12 } 13 }
1 class circle extends shape
2 {//子类继承父类 3 public static double getArea(int radius) 4 { 5 return radius*radius*pi; 6 } 7 8 9 public static double getPerimeter(int radius) 10 { 11 return 2*pi*radius; 12 } 13 }
1 class shape
2 {//父类 3 private static String rect; 4 private static String cir; 5 public double width;//成员变量 6 public double length; 7 public double area; 8 public double Perimeter; 9 final static double pi=3.1415926; 10 final static String n=rect; 11 final static String m=cir; 12 13 public double getArea() 14 {//成员方法 15 return area; 16 } 17 18 19 public double getPerimeter() 20 { 21 return Perimeter; 22 } 23 }
实验3: 编程练习2
编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。
1 package check;
2 public class Student { 3 4 private String name; 5 private String number ; 6 private String sex ; 7 private String year; 8 private String province; 9 10 public String getName() { 11 return name; 12 } 13 public void setName(String name) { 14 this.name = name; 15 } 16 public String getnumber() { 17 return number; 18 } 19 public void setnumber(String number) { 20 this.number = number; 21 } 22 public String getsex() { 23 return sex ; 24 } 25 public void setsex(String sex ) { 26 this.sex =sex ; 27 } 28 public String getyaer() { 29 return year; 30 } 31 public void setyear(String year ) { 32 this.year=year ; 33 } 34 public String getprovince() { 35 return province; 36 } 37 public void setprovince(String province) { 38 this.province=province ; 39 } 40 }
1 package check;
2 import java.io.*; 3 import java.util.*; 4 public class Check{ 5 private static ArrayList<Student> studentlist; 6 public static void main(String[] args) 7 { 8 studentlist = new ArrayList<>(); 9 Scanner scanner = new Scanner(System.in); 10 File file = new File("C:\\下载\\身份证号.txt"); 11 try 12 { 13 FileInputStream fis = new FileInputStream(file); 14 BufferedReader in = new BufferedReader(new InputStreamReader(fis)); 15 String temp = null; 16 while ((temp = in.readLine()) != null) 17 { 18 Scanner linescanner = new Scanner(temp); 19 linescanner.useDelimiter(" "); 20 String name = linescanner.next(); 21 String number = linescanner.next(); 22 String sex = linescanner.next(); 23 String year = linescanner.next(); 24 String province =linescanner.nextLine(); 25 Student student = new Student(); 26 student.setName(name); 27 student.setnumber(number); 28 student.setsex(sex); 29 student.setyear(year); 30 student.setprovince(province); 31 studentlist.add(student); 32 } 33 } 34 catch (FileNotFoundException e) 35 { 36 System.out.println("学生信息文件找不到"); 37 e.printStackTrace(); 38 } 39 catch (IOException e) 40 { 41 System.out.println("学生信息文件读取错误"); 42 e.printStackTrace(); 43 } 44 boolean isTrue = true; 45 while (isTrue) 46 { 47 System.out.println("1.按姓名查询"); 48 System.out.println("2.按身份证号查询"); 49 System.out.println("3.退出"); 50 int nextInt = scanner.nextInt(); 51 switch (nextInt) 52 { 53 case 1: 54 System.out.println("请输入姓名"); 55 String studentname = scanner.next(); 56 int nameint = findStudentByname(studentname); 57 if (nameint != -1) { 58 System.out.println("查找信息为:身份证号:" 59 + studentlist.get(nameint).getnumber() + " 姓名:" 60 + studentlist.get(nameint).getName() +" 性别:" 61 +studentlist.get(nameint).getsex() +" 年龄:" 62 +studentlist.get(nameint).getyaer()+" 地址:" 63 +studentlist.get(nameint).getprovince() 64 ); 65 } 66 else 67 { 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 { 77 System.out.println("查找信息为:身份证号:" 78 + studentlist.get(idint ).getnumber() + " 姓名:" 79 + studentlist.get(idint ).getName() +" 性别:" 80 +studentlist.get(idint ).getsex() +" 年龄:" 81 +studentlist.get(idint ).getyaer()+" 地址:" 82 +studentlist.get(idint ).getprovince() 83 ); 84 } 85 else 86 { 87 System.out.println("不存在该学生"); 88 } 89 break; 90 case 3: 91 isTrue = false; 92 System.out.println("程序已退出!"); 93 break; 94 default: 95 System.out.println("输入有误"); 96 } 97 } 98 } 99 100 public static int findStudentByname(String name) 101 { 102 int flag = -1; 103 int a[]; 104 for (int i = 0; i < studentlist.size(); i++) 105 {