实验六201771010101 白玛次仁
第五章 继承 总结
实验六 继承定义与使用实验时间 2018-9-28
1.类,超类与子类
继承Employee类来定义Manager类格式,关键字extends表示继承。
Class新类名(子类(subclass),派生类(derived class)或孩子类(chide class))。
extends已有类名(超类(superclass),基类(base class)或父类(parent class))。
一般来说,子类比超类拥有的功能更加丰富。
子类不能直接访问超类的私有域,必须和其他方法一样——使用公有接口。
super是一个指示编译器调用超类方法的特有关键字,它不是一个对象的引用,不能将super赋给另一个对象变量
从一个超类扩展而来的类集合称为继承层次。在继承层次中,某个类到其祖先的路径被称为该类的继承链。
Java不支持多继承。
2.多态性:泛指在程序中同一个符号在不同的情况下具有不同解释的现象。
超类中的方法在子类中可方法重写。
3.抽象类:抽象方法充当着占位的角色,它们的具体实现在子类中。(抽象类只能产生子类。)
4.Object:所有类的超类: Java中所有类的祖先——每一个类都由它扩展而来。在不给出超类的情况下,Java会自动把Object 作为要定义类的超类。(它们进行专门的操作都要进行类型转换。)
Object类中的equals方法用于测试某个对象是否同另一个对象相等。它在Object类中的实现是判断两个对象是否具有相同的引用。如果两个对象具有相同的引用,它们一定是相等的。
Object类中的hashCode方法导出某个对象的散列码。散列码是任意整数,表示对象的存储地址。(两个相等对象的散列码相等)
5.泛型数组列表
ArryList是一个采用类型参数的泛型类。为指定数组列表保存元素的对象类型,需要用一对尖括号将数组元素对象类名括起来加在后面。
ArryList<Employee> staff=new ArrayList<Employee>();
6.对象包装器与自动装箱:
所有基本数据类型都有着与之对应的预定义类,它们被称为对象包装器。
对象包装器类是不可变的,即一旦构造了包装器,就不允更改包装在其中的值。且对象包装器类还是final,因此不能定义它们的子类。
自动的将基本数据类型转换为包装器类的对象,将这种变换称为自动打包
7.参数数量可变的方法、
用户自己可以定义可变参数的方法,并将参数指定为任意类型,甚至是基本类型。
8.枚举类
publicenumGrade{A,B,C,D,E};
它包括一个关键字enum,一个新枚举类型的名字 Grade以及为Grade定义的一组值,这里的值既非整型,亦非字符型。
枚举值并不是整数或其它类型,是被声明的枚举类的自身实例
9.反射
10.继承的设计技巧
使用继承实现“is-a”关系。
在覆盖方法时,不要改变预期的行为。
将公共操作和域放在超类。
使用多态,而非类型信息。
2.实验目的
(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)
{
// 创建类
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);
// 打印所有员工类的基本信息
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}
employee类
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类
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;
}
测试程序2:
Ÿ 编辑、编译、调试运行教材PersonTest程序(教材163页-165页);
Ÿ 掌握超类的定义及其使用要求;
Ÿ 掌握利用超类扩展子类的要求;
Ÿ 在程序中相关代码处添加新知识的注释。
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];
// 用学生数组
people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
people[1] = new Student("Maria Morris", "computer science");
// 打印对象的名称和描述
for (Person p : people)
System.out.println(p.getName() + ", " + p.getDescription());
}
}
package abstractClasses;
public class Student extends Person
{
private String major;
/**
* @param nama the student's name
* @param major the student's major
*/
public Student(String name, String major)
{
// 构造函数
super(name);
this.major = major;
}
public String getDescription()
{
return "a student majoring in " + major;
}
}
person类
package abstractClasses;
public abstract class Person
{
//包含一个或多个抽象方法的类被称为抽象类
//通用的作用域和方法也放到了这里
public abstract String getDescription();
private String name;
public Person(String name)
{
this.name = name;
}
public String getName()
{ return name;
}
}
employee类
package abstractClasses;
import java.time.*;
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;
}
}
程序运行结果如下:
测试程序3:
Ÿ 编辑、编译、调试运行教材程序5-8、5-9、5-10,结合程序运行结果理解程序(教材174页-177页);
Ÿ 掌握Object类的定义及用法;
Ÿ 在程序中相关代码处添加新知识的注释。
package abstractClasses;
person类
package abstractClasses;
public abstract class Person
{
//包含一个或多个抽象方法的类被称为抽象类
//通用的作用域和方法也放到了这里
public abstract String getDescription();
private String name;
public Person(String name)
{
this.name = name;
}
public String getName()
{ return name;
}
}
employee类
package abstractClasses;
import java.time.*;
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;
}
}
程序运行结果如下:
测试程序3:
Ÿ 编辑、编译、调试运行教材程序5-8、5-9、5-10,结合程序运行结果理解程序(教材174页-177页);
Ÿ 掌握Object类的定义及用法;
Ÿ 在程序中相关代码处添加新知识的注释。
3)在程序中相关代码处添加新知识的注释。
程序5-8如下:
package equals;
/**
* This program demonstrates the equals method.
* @version 1.12 2012-01-26 6 * @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());
}
}
Manager类
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;28
// 检查这个和其他属于同一个类
return bonus == other.bonus;
}
{
return java.util.Objects.hash(super.hashCode(), bonus);
}
public String toString()
{
return super.toString() + "[bonus=" + bonus + "]";
}
}
employee类
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;
if (otherObject == null) return false;
// getClass()方法是得到对象的类
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);
} // toString()
public String toString()
return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
+ "]";
}
}
程序运行结果:
测试程序4:
Ÿ 在elipse IDE中调试运行程序5-11(教材182页),结合程序运行结果理解程序;
Ÿ 掌握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)
{
// 用三个雇员对象填充工作人员数组列表
var staff = new ArrayList<Employee>();
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
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页),结合运行结果理解程序;
Ÿ 掌握枚举类的定义及用法;
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)//程序入口
{
var in = new Scanner(System.in);//构造一个Scanner类
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
[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 Cin;
import Cin. Shape; class 圆形 extends Shape{
private double PI=3.14;
private int r;
public void 圆形(int r) {
this.r = r;
}
double getPerimeter(){
return 2 * PI * r;
}
double getArea(){
return r * r*PI;
}
}
package Cin;
import Cin. Shape;
class 长方形 extends Shape{
private int width;
private int length;
public 长方形(int width2, int length2) { // TODO Auto-generated constructor stub }
public void 长方形(int length, int width) {
this.width = width;
this.length = length;
}
double getPerimeter(){
return 2*(length+width);
} double getArea(){ return length*width; } }
package Cin;
import Cin.Shape;
abstract class Shape { //定义抽象父类Shape abstract double getPerimeter(); //定义求解周长的方法 abstract double getArea(); //定义求解面积的方法 }
class Rectangle extends Shape{ private int length;
private int width; public Rectangle(int length, int width) {
this.length = length; this.width = width; } //继承父类 double getPerimeter(){ //调用父类求周长的方法 return 2*(length+width); } double getArea(){ return length*width; //调用父类求面积的方法 } }
class Circle extends Shape{ private int radius;
public Circle(int radius) { this.radius = radius; }
double getPerimeter(){ return 2 * Math.PI * radius; } double getArea(){ return Math.PI * radius * radius; } }
package Cin; import Cin.Shape; import Cin.Test; import Cin.圆形; import Cin.长方形; import java.util.Scanner; public class Test { double PI=3.14;
public double AllArea(Shape score[])
{
double sum=0;
for(int i=0;i<score.length;i++)
sum+= score[i].getArea();
return sum;
}
public double AllPerimeter(Shape score[])
{
double sum=0;
for(int i=0;i<score.length;i++)
sum+= score[i].getPerimeter();
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入创建图形的个数");
int a = in.nextInt();
System.out.println("请输入图形种类(选择输入cir或rect)");
String rect="rect";
String cir="cir";
Shape[] num=new Shape[a];
for(int i=0;i<a;i++){
String input=in.next();
if(input.equals(rect)) {
System.out.println("请输入长和宽");
int width = in.nextInt();
int length = in.nextInt();
num[i]=new 长方形(width,length);
System.out.println("长方形["+"长方形的长为:"+length+" 长方形的宽为:"+width+"]");
}
if(input.equals(cir)) {
System.out.println("输入所创建的圆的半径");
int r = in.nextInt();
num[i]=new 圆形();
System.out.println("圆["+"圆的半径为:"+r+"]");
}
}
Test c=new Test();
System.out.println("求所有图形的面积和:");
System.out.println(c.AllPerimeter(num));
System.out.println("求所有图形的周长和:");
System.out.println(c.AllArea(num));
for(Shape s:num) {
System.out.println(s.getClass()+","+s.getClass().getSuperclass()); } } }
实验3: 编程练习2
编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。
package zbiuhxb;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;import java.util.ArrayList;
import java.util.Scanner;
public class Identity {
private static ArrayList<Student>studentlist = null;
public static void main(String args[]) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("c:/身份证号.txt" );
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String temp = null;
while ((temp = reader.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String number = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String province =linescanner.nextLine();
Student student = new Student();
student.setName(name);
student.setnumber(number);
student.setsex(sex);
student.setage(age);
student.setprovince(province);
studentlist.add(student);
}
reader.close();
} catch (IOException e) { //读错 e.printStackTrace();
}
int status=1;
while (status!=0)
{
System.out.println("1:通过姓名查询");
System.out.println("2:通过身份证号查询");
System.out.println("0:退出");
status = scanner.nextInt();
switch (status) {
case 1:
System.out.println("请输入姓名:");
String scanner1 = scanner.next();
int nameint = findStudentByName(scanner1);
if(nameint != -1) {
System.out.println("查找信息为:身份证号:"
+ studentlist.get(nameint).getnumber() + " 姓名:"
+ studentlist.get(nameint).getName() +" 性别:"
+studentlist.get(nameint).getsex() +" 年龄:"
+studentlist.get(nameint).getage()+" 地址:"
+studentlist.get(nameint).getprovince()
);
} break;
case 2:
System.out.println("请输入身份证号:");
String studentid = scanner.next();
int id = findStudentById(studentid);
if (id != -1) {
System.out.println("查找信息为:身份证号:"
+ studentlist.get(id ).getnumber() + " 姓名:"
+ studentlist.get(id ).getName() +" 性别:"
+studentlist.get(id ).getsex() +" 年龄:"
+studentlist.get(id ).getage()+" 地址:"
+studentlist.get(id ).getprovince()
);
}break;
case 0:
status = 0;
System.out.println("程序已退出!");
break;
default:
System.out.println("输入错误");
}
}
}
public static int findStudentByName(String name) {
int flag = -1;
int a[];
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).getnumber().equals(id)) {
flag = i;
}
}
return flag;
}
}
package zbiuhxb;
public class Student {
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 ;
}
}
运行结果:
实验总结:通过本次实验什么都在瞎折腾,明确明白我啥都没学上。