理论知识学习部分
类继承的格式: class 新类名 extends 已有类名(子类比超类拥有的功能更加丰富。)
继承层次:Java不支持多继承。
多态性:Java中,对象变量是多态的;不能把对超类的对象引用赋给子类对象变量。
阻止继承:
不允许继承的类称为final类,在类的定义中用final修饰 符加以说明。
finalclass Executive extends Manager
{ …… }
抽象类:abstractclass Person {
publicabstractString getDescription( );
…... }
Object:所有类的超类
(1)equals方法:Object类中的equals方法用于测试某个对象是否同另一 个对象相等。它在Object类中的实现是判断两个对象是 否具有相同的引用。如果两个对象具有相同的引用,它 们一定是相等的。
(2)定义子类的equals方法时,可调用超类的equals方法。 super.equals(otherObject)
(3)toString方法:Object类的toString方法返回一个代表该对象域值的字符串。
泛型数组列表:Java中,利用ArrayList类,可允许程序在运行 时确定数组的大小。ArryList是一个采用类型参数的泛型类。为指定 数组列表保存元素的对象类型
ArryList<Employee> staff=new ArrayList<Employee>();
枚举类:枚举类是一个类,它的隐含超类是java.lang.Enum
枚举值并不是整数或其它类型,是被声明的枚举类的 自身实例;
枚举类不能有public修饰的构造函数,构造函数都是 隐含private,编译器自动处理。枚举值隐含都是由public、static、final修饰的,无 须自己添加这些修饰符。
在比较两个枚举类型的值时,永远不需要调用equals 方法,直接使用"=="进行相等比较。
声明枚举类:publicenumGrade{A,B,C,D,E};
实验部分
1、实验目的与要求
(1) 理解继承的定义;
(2) 掌握子类的定义要求
(3) 掌握多态性的概念及用法;
(4) 掌握抽象类的定义及用途;
(5) 掌握类中4个成员访问权限修饰符的用途;
(6) 掌握抽象类的定义方法及用途;
(7)掌握Object类的用途及常用API;
(8) 掌握ArrayList类的定义方法及用法;
(9) 掌握枚举类定义方法及用途。
2、实验内容和步骤
实验1:
ManagerTest.java
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对象 Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); boss.setBonus(5000); Employee[] staff = new Employee[3]; // 将Manager和Employee填入数组 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()); } }
Employee.java
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; } }
Manager.java
package inheritance; //构造一个新的子类Manager继承父类Employee 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 */ //调用父类中的name,salary,year,month,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; } }
输出结果:
测试程序2:
PersonTest.java
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[] people = new Person[2]; //用Student和Employee对象填充Person数组 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()); } }
Person.java
package abstractClasses; //定义抽象类Person public abstract class Person { //增加getDescription方法,添加对一个人的简短描述 public abstract String getDescription(); private String name; public Person(String name) { this.name = name; } public String getName() { return name; } }
Employee.java
package abstractClasses; import java.time.*; //构造新的子类Employee继承父类Person 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; } }
Student.java
package abstractClasses; public class Student extends Person //构造新的子类Student继承父类Person { private String major; /** * @param nama the student's name * @param major the student's major */ public Student(String name, String major) { //将n传给父类构造器 super(name); this.major = major; } public String getDescription() { return "a student majoring in " + major; } }
输出结果:
测试程序3:
Equals.java
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()); } }
Employee.java
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 (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; //现在已知otherObject是一个非空雇员 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 + "]"; } }
Manager.java
package equals; public class Manager extends Employee //构建子类Manager继承父类Employ { 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; //检查this和other属于同一个类 return bonus == other.bonus; } public int hashCode() { return java.util.Objects.hash(super.hashCode(), bonus); } public String toString() { return super.toString() + "[bonus=" + bonus + "]"; } }
输出结果:
测试程序4:
ArraryListTest.java
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()); } }
Employee.java
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:
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
ShapeTest.java
package shape; import java.util.*; public class ShapeTest { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.println("n的值为:"); int n=in.nextInt(); String Rectangle = "rect"; String Circle = "cir"; shape[] staff = new shape[n]; for(int i=0;i<n;i++) { //System.out.println("图形形状为:"); String input = in.next(); if(input.equals("rect")) { //System.out.print("长方形的长和宽为:"); double width = in.nextDouble(); double length = in.nextDouble(); System.out.println("Rectangle ["+"length="+length+" width="+width+"]"); staff[i] = new Rectangle(width,length); } if(input.equals("cir")) { //System.out.print("圆形半径为:"); double radius = in.nextDouble(); System.out.println("Circle ["+"radius="+radius+"]"); staff[i] = new Circle(radius); } } ShapeTest rescult = new ShapeTest(); System.out.println(rescult.sumAllPerimeter(staff)); System.out.println(rescult.sumAllArea(staff)); } public double sumAllPerimeter(shape staff[]) { double sum = 0; for(int i = 0;i<staff.length;i++) sum+= staff[i].getPerimeter(); return sum; } public double sumAllArea(shape staff[]) { double sum = 0; for(int i = 0;i<staff.length;i++) sum += staff[i].getArea(); return sum; } }
Shape.java
package shape; public abstract class shape { public abstract double getPerimeter(); public abstract double getArea(); double PI = 3.14; }
Rectangle.java
package shape; public class Rectangle extends shape{ private double width; private double length; public Rectangle(double x,double y) { this.width = x; this.length = y; } public double getPerimeter() { double Perimeter = (width+length)*2; return Perimeter; } public double getArea() { double Area = width*length; return Area; } }
Circle.java
package shape; public class Circle extends shape{ private double radius; public Circle(double r) { this.radius = r; } public double getPerimeter() { double Perimeter = 2*PI*radius; return Perimeter; } public double getArea() { double Area = radius*radius*PI; return Area; } }
输出结果:
实验3:编程练习2
IDcheck.java
package IDcheck; 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.Scanner; import java.util.ArrayList; public class IDcheck { private static ArrayList<Identify> identifylist; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); File file = new File("E:\身份证号.txt"); identifylist = new ArrayList<>(); try { FileInputStream files = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(files)); String temp = null; while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" "); String name = linescanner.next(); String IDnumber = linescanner.next(); String sex = linescanner.next(); String year = linescanner.next(); String bornplace =linescanner.nextLine(); Identify identify = new Identify(); identify.setName(name); identify.setIDnumber(IDnumber); identify.setsex(sex); identify.setage(year); identify.setbornplace(bornplace); identifylist.add(identify); } } 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 ID = scanner.next(); Identify identify = findIdentifyByidnumber(ID); if (identify != null) { System.out.println("姓名:"+ identify.getName()+ " 身份证号:"+ identify.getnumber()+ " 年龄:"+ identify.getage()+ " 性别:"+ identify.getsex()+ " 地址:"+ identify.getbornplace()); } else { System.out.println("查无此人"); }break; case 2: System.out.println("请输入姓名:"); String name = scanner.next(); Identify fullname = findIdentifyByname(name); if (fullname != null) { System.out.println("姓名:"+ fullname.getName() + " 身份证号:"+ fullname.getnumber() + " 年龄:"+ fullname.getage()+ " 性别:"+ fullname.getsex()+ " 地址:"+ fullname.getbornplace() ); } else { System.out.println("查无此人"); } break; case 3: isTrue = false; System.out.println("错误!"); break; } } } private static Identify findIdentifyByidnumber(String ID) { Identify flag = null; for (Identify people : identifylist) { if(people.getnumber().equals(ID)) { flag = people; } } return flag; } private static Identify findIdentifyByname(String name) { Identify flag = null; for (Identify people : identifylist) { if(people.getName().equals(name)) { flag = people; } } return flag; } }
Identify.java
package IDcheck; public class Identify { private String name; private String IDnumber; private String age; private String sex; private String bornplace; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getnumber() { return IDnumber; } public void setIDnumber(String IDnumber) { this.IDnumber = IDnumber; } 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 getbornplace() { return bornplace; } public void setbornplace(String bornplace) { this.bornplace = bornplace; } }
输出结果:
实验总结:通过对第五章的学习,我了解到了java中继承的作用,程序中有包含关系的类都可以使用继承,子类可以继承父类的所有属性和方法,继承可以提高代码的重用性和程序的拓展性。重写可以拓展父类的方法,更好的适应子类的需要。同时我也学到了一些继承的设计技巧,如将公共操作和域放在超类,但是除非继承的方法有意义,否则不使用继承......关于java我学习到了java支持面向对象编程的基础内容:类、继承,多态。但是我还是会不断地去完善自己的知识。