李晓菁201771010114《面向对象程序设计(Java)》第六周学习总结
理论部分:
第五章:继承
1.继承用已有类来构建新类的一种机制。
2..继承的特点:具有层次结构,子类继承了父类的域和方法。
3.继承的优点:代码可重用性,父类的域和方法可用于子类,可以轻松定义子类,设计应用程序变得更加简单。
4.类,超类,子类:
class 新类名 extends已有类名
已有类称为:超类,基类或父类。
新类称为:子类 派生类。
一般来说,子类比超类拥有的功能更加丰富。
5.通过扩展超类定义子类时,仅需要指出超类与子类的不同之处。super是一个指示编译器调用超类方法的特有关键字。他不是一个对象的引用,不能将super赋值给另一个超类变量。
若子类构造器没有显示的调用超类的构造器,则将自动的调用超类默认构造器。
6.多态性:
多态性泛指在程序中同一符号在不同情况下具有不同解释的现象。
超类中定义的域或方法,被子类继承之后,可以具有不同的数据类型或表现出不同的行为。
这使得同一域或方法在超类及其各个子类中具有不同的语义。
实验六 继承定义与使用
实验时间 2018-9-28
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; /** * This program demonstrates inheritance. * * @version 1.21 2004-02-21 * @author Cay Horstmann */ public class ManagerTest { public static void main(String[] args) { // construct a Manager object Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);// 执行完该行之后bonus为0 boss.setBonus(5000);//set调用更改器方法将bonus改为5000 Employee[] staff = new Employee[3];//定义一个Employee类,new后使用构造器方法并将该数组初始化为3。 // fill the staff array with Manager and Employee objects staff[0] = boss;//boss是Employee类的子类对象。 staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15); //staff也是Employee类。 // print out information about all Employee objects for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());//使用get调用访问器 方法 } }
package inheritance; public class Manager extends Employee { 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); bonus = 0; } public double getSalary() { 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) { // construct a Manager object Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); boss.setBonus(5000); Employee[] staff = new Employee[3]; // fill the staff array with Manager and Employee objects staff[0] = boss; staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15); // print out information about all Employee objects for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary()); } }
运行结果:
测试程序2:
Ÿ 编辑、编译、调试运行教材PersonTest程序(教材163页-165页);
Ÿ 掌握超类的定义及其使用要求;
Ÿ 掌握利用超类扩展子类的要求;
Ÿ 在程序中相关代码处添加新知识的注释。
/** * This program demonstrates abstract classes. * @version 1.01 2004-02-21 * @author Cay Horstmann */ public class PersonTest//主类 { public static void main(String[] args) { Person[] people = new Person[2]; //用Employee类和Student类填充people数组 people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1); people[1] = new Student("Maria Morris", "computer science"); //打印出所有person类的名字和其他描述 for (Person p : people) System.out.println(p.getName() + ", " + p.getDescription()); } }
public abstract class Person//抽象类:Person { public abstract String getDescription(); private String name;//传建一个私有属性 public Person(String name)//构造器 { this.name = name; } public String getName()//访问器 { return name; } }
public class Student extends Person//子类:Student类继承Person类 { private String major;//创建一个私有属性major /** * @param nama the student's name * @param major the student's major */ public Student(String name, String major)//构造器 { super(name);//子类直接调用超类中的name属性 this.major = major; } public String getDescription()//访问器 { return "a student majoring in " + major; } } import java.time.*; public class Employee extends Person//子类:Employee类继承Person类 { private double salary; private LocalDate hireDay; //两个私有属性 public Employee(String name, double salary, int year, int month, int day)//构造器 { super(name);//子类直接调用超类中的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; }//定义两个局部变量 }
运行结果:
测试程序3:
Ÿ 编辑、编译、调试运行教材程序5-8、5-9、5-10,结合程序运行结果理解程序(教材174页-177页);
Ÿ 掌握Object类的定义及用法;
Ÿ 在程序中相关代码处添加新知识的注释。
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 + "]"; } }
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 (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 + "]"; } }
运行结果:
测试程序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) { // 用三个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类:
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
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 demo1; import java.util.Scanner; public class Text1 { public static void main(String[] args) { // TODO 自动生成的方法存 @SuppressWarnings("resource") Scanner in = new Scanner(System.in); String rect = "rect"; String cir = "cir"; System.out.println("请输入不同的形状个数:"); int n = in.nextInt(); shape[] num = new shape[n]; for (int i = 0; i < n; i++) { System.out.println("请输入形状类型 (rect or cir):"); String input = in.next(); if (input.equals(rect)) { System.out.println("长和宽"); double length = in.nextDouble(); double width = in.nextDouble(); System.out.println("Rectangle[" + "length:" + length + " width:" + width + "]"); num[i] = new Rectangle(width, length); } if (input.equals(cir)) { System.out.println("半径 "); double radius = in.nextDouble(); System.out.println("Circle[" + "radius:" + radius + "]"); num[i] = new Circle(radius); } } Text1 c = new Text1(); 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; } }
抽象类Shape:
public abstract class shape { double PI = 3.14; abstract double getPerimeter(); abstract double getArea(); }
circle类:
public class Circle extends shape { private double radius; public Circle(double radius) { } public double getPerimeter() { double Perimeter=2*PI*radius; return Perimeter; } public double getArea() { double Area=PI*radius*radius; return Area; } }
Rectangle类:
public class Rectangle extends shape { private double length; private double width; public Rectangle(double width, double length) { this.length = length; this.width = width; } public double getPerimeter() { double Perimeter=2*(length + width); return Perimeter ; } public double getArea() { double Area= length * width; return Area; } }
运行结果:
实验3: 编程练习2
编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。
程序如下:
package demo2; 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 Demo2 { private static ArrayList<Student> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); File file = new File("D:\\身份证号\\身份证号.txt"); try { FileInputStream fis = new FileInputStream(file); @SuppressWarnings("resource") BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; while ((temp = in.readLine()) != null) { @SuppressWarnings("resource") 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) { // TODO Auto-generated catch block System.out.println("所找信息文件读取错误"); e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("欢迎来到信息查询系统,请选择你的操作"); 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).getYear() + " 地址:" + 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).getYear() + " 地址:" + 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; 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).getId().equals(id)) { flag = i; } } return flag; } }
封装类如下所示:
public class Student { private String name; private String id; 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 getId() { return id; } public void setId(String id) { this.id = id; } public String getNumber() { // TODO 自动生成的方法存根 return number; } public void setNumber(String number) { this.number = number; } public String getSex() { // TODO 自动生成的方法存根 return sex; } public void setSex(String sex) { // TODO 自动生成的方法存根 this.sex = sex; } public String getYear() { // TODO 自动生成的方法存根 return year; } public void setYear(String year) { // TODO 自动生成的方法存根 this.year = year; } public String getProvince() { // TODO 自动生成的方法存根 return province; } public void setProvince(String province) { // TODO 自动生成的方法存根 this.province = province; } }
运行结果如下:
实验总结:通过本次实验二让我更加明确了封装的概念,以及读取文件的操作,通过实验一让我更进一步的理解了继承的概念,在此次代码注释过程中,我发现了自己的不足之处在于,对有些代码还是不太清楚其语义,以及其含义,上次老师讲授代码的含义时,对我帮助极大,希望老师还可以选择讲一些代码的作用。这样在我自己学习时,就可结合老师的讲授去理解。