张季跃 201771010139《面向对象程序设计(java)》第六周学习总结
张季跃201771010139《面向对象程序设计(java)》第六周学习总结
第一部分:理论知识学习部分
第五章继承:
继承:用已有类来构建新类的一种机制。当定义了一个新类继承了一个类时,这个新类就继承了这个类的方法和域,同时在新类中添加新的方法和域以适应新的情况。l
继承是Java程序设计中的一项核心技术,也是 面向对象特征之一。
5.1l类、超类和子类:
l1.类继承的格式:class 新类名extends已有类名
已有类称为:超类(superclass)、基类(base class) 或父类(parent class)
–来自系统类库
–用户自定义类
新类称作:子类(subclass)、派生类(derived class)或孩子类(child class)
l2.一般来说,子类比超类拥有的功能更加丰富3.2数据类型
Java共有8种基本类型 :
l(1)从一个超类扩展而来的类集合称为继承层次 (inheritancehierarchy)。在继承层次中,从 某个类到其祖先的路径被称为该类的继承链 (inheritancechain)。 l
(2)Java不支持多继承
4. 动态绑定
l 动态绑定的概念:又称为运行时绑定。意思是说,程序在运行时 会自动选择调用哪个方法。
5.阻止继承:final类和方法
l(1)不允许继承的类称为final类,在类的定义中用final修饰 符加以说明。
(2)类中的方法可定义为final的。这时子类就不能覆盖该方法。 l
(3)如果一个类声明为final,属于它的方法会被自动设为 final,但不包括域(如果域定义为final,在对象构造以 后,final域就不能再修改了)。 private final intMax = 100; l
(4)String类是final类的一个例子。不能扩展该类。
l(1)如果要把一个超类对象赋给一个子类对象变量,就必须进 行强制类型转换。
(2)类型转换必须在继承层次内进行;而且在超类到子类转换 之前,应先使用instanceof操作符进行继承链检查。
7.抽象类:
观察类的继承层次结构,位于上层的类更具通用性,甚至可能更加抽象。从某种角度看,祖先类更加通用,人们只将它作为派生其他类的基类,而不作为特定的实例类。
8.受保护访问:
(1)如果希望超类的某些方法或域允许被子类访问,就需要在超类定义时,将这些方法或域声明为protected。 l
(2)实际中要谨慎使用protected的属性。假设需要将设计的类 提供给其他程序员使用,而在这个类中设置了一些受保护 域,由于其他程序员可以由这个类再派生出新类,并访问 其中的受保护域。在这种情况下,如果对这个类进行修改 ,就必须通知所有使用这个类的程序员。这违背了OOP提倡 的数据封装原则。 l
(3)如果定义类时要限制某个方法的使用,就可以将它声明为protected。这表明子类得到信任,可以使用这个方法,而 其他类则不行。
5.2 Object:所有类的超类
l1.Object类是Java中所有类的祖先——每一个类都由它扩 展而来。在不给出超类的情况下,Java会自动把Object 作为要定义类的超类。 l
(1)Object类中的equals方法用于测试某个对象是否同另一 个对象相等。它在Object类中的实现是判断两个对象是 否具有相同的引用。如果两个对象具有相同的引用,它 们一定是相等的。 l
(2)如果需要检测两个对象状态的相等性,就需要在新类的定义中需要覆盖equals方法。
(3)定义子类的equals方法时,可调用超类的equals方法。
(1)Object类中的hashCode方法导出某个对象的散列 码。散列码是任意整数,表示对象的存储地址。 l
(2)两个相等对象的散列码相等。
(1)Object类的toString方法返回一个代表该对象域值的字符串。 l
(a)一个字符串与对象名通过操作符“+”连接起来,就会 自动调用toString方法。
(b)如果x是任意一个对象,调用System.out.println(x), 就会直接地调用x.toString(),并打印输出字符串。 l
(2)定义子类的toString方法时,可先调用超类的toString方法。
(3)toString方法是非常重要的调试工具。标准类库中,多数类 定义了toString方法,以便用户获得对象状态的必要信息。
5.3泛型数组列表
l 1.Java中,利用ArrayList类,可允许程序在运行 时确定数组的大小。 l
(1)a.ArrayList定义 l
(2)API:booleanadd(T obj) 把元素obj追加到数组列表的结尾
(3)API:intsize() 返回数组列表中当前元素个数
(4)API:void trimToSize() 把数组列表的存贮空间调整到当前大小
(5)API:void set(intindex, T obj) 将obj放入数组列表index位置,将覆盖这 个位置的原有内容。
API:T get(intindex) 获得指定位置index的元素值
(6)API:booleanadd(intindex, T obj) 向后移动元素,在第n 个位置插入obj
API:T remove(intindex); 将第n个位置存放的对象删除,并将后面的 元素向前移
5.4 对象包装器与自动打包
l 1.所有基本数据类型都有着与之对应的预定义类,它们被称 为对象包装器(wrapper)。 l
在JavaSE5.0中,可以自动的将基本数据类型转换 为包装器类的对象,将这种变换称为自动打包 (autoboxing)。
5.5 参数数量可变的方法
l 1.在Java SE 5.0以前的版本中,每个Java方法都 有固定数量的参数。然而,现在的版本提供了可 以用可变的参数数量调用的方法(称为“可变参 ”方法)。
2.用户自己可以定义可变参数的方法,并将参数指 定为任意类型,甚至是基本类型
5.6 枚举类
1.声明枚举类:它包括一个关键字enum,一个新枚举类型的名字 Grade以及为Grade定义的一组值,这里的值既 非整型,亦非字符型。
5.7 继承设计的技巧
①将公共操作和域放在超类。
②不要使用受保护的域。
③使用继承实现“is-a”关系。
④除非所有继承的方法都有意义,否则就不要 使用继承。
⑤在覆盖方法时,不要改变预期的行为。
⑥使用多态,而非类型信息。 ⑦不要过多地使用反射。
第二部分:实验部分
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类的关系子类的用途,并在代码中添加注释。
测试程序:
packageinheritance;
importjava.time.*;
publicclassEmployee
{
privateStringname;
privatedoublesalary;
privateLocalDatehireDay;
publicEmployee(Stringname,doublesalary,intyear,intmonth,intday)
{
this.name=name;
this.salary=salary;
hireDay= LocalDate.of(year,month,day);
}
publicString getName()
{
returnname;
}
publicdoublegetSalary()
{
returnsalary;
}
publicLocalDate getHireDay()
{
returnhireDay;
}
publicvoidraiseSalary(doublebyPercent)
{
doubleraise=salary*byPercent/ 100;
salary+=raise;
}
}
packageinheritance;
publicclassManagerextendsEmployee
{
privatedoublebonus;
/**
*@paramname the employee's name
*@paramsalary the salary
*@paramyear the hire year
*@parammonth the hire month
*@paramday the hire day
*/
publicManager(Stringname,doublesalary,intyear,intmonth,intday)
{
super(name,salary,year,month,day);
bonus= 0;
}
publicdoublegetSalary()
{
doublebaseSalary=super.getSalary();
returnbaseSalary+bonus;
}
publicvoidsetBonus(doubleb)
{
bonus=b;
}
}
packageinheritance;
/**
* This program demonstrates inheritance.
*@version1.21 2004-02-21
*@authorCayHorstmann
*/
publicclassManagerTest
{
publicstaticvoidmain(String[]args)
{
// construct a Manager object
Managerboss=newManager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[]staff=newEmployee[3];
// fill the staff array with Manager and Employee objects
staff[0] =boss;
staff[1] =newEmployee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] =newEmployee("Tommy Tester", 40000, 1990, 3, 15);
// print out information about all Employee objects
for(Employeee:staff)
System.out.println("name="+e.getName() +",salary="+e.getSalary());
}
}
测试结果:
测试程序2:
Ÿ编辑、编译、调试运行教材PersonTest程序(教材163页-165页);
Ÿ掌握超类的定义及其使用要求;
Ÿ掌握利用超类扩展子类的要求;
Ÿ在程序中相关代码处添加新知识的注释。
测试程序:
packageabstractClasses;
importjava.time.*;
publicclassEmployeeextendsPerson
{
privatedoublesalary;
privateLocalDatehireDay;
publicEmployee(Stringname,doublesalary,intyear,intmonth,intday)
{
super(name);
this.salary=salary;
hireDay= LocalDate.of(year,month,day);
}
publicdoublegetSalary()
{
returnsalary;
}
publicLocalDate getHireDay()
{
returnhireDay;
}
publicString getDescription()
{
returnString.format("an employee with a salary of $%.2f",salary);
}
publicvoidraiseSalary(doublebyPercent)
{
doubleraise=salary*byPercent/ 100;
salary+=raise;
}
}
packageabstractClasses;
publicabstractclassPerson
{
publicabstractString getDescription();
privateStringname;
publicPerson(Stringname)
{
this.name=name;
}
publicStringgetName()
{
returnname;
}
}
packageabstractClasses;
/**
* This program demonstrates abstract classes.
*@version1.01 2004-02-21
*@authorCayHorstmann
*/
publicclassPersonTest
{
publicstaticvoidmain(String[]args)
{
Person[]people=newPerson[2];
// fill the people array with Student and Employee objects
people[0] =newEmployee("Harry Hacker", 50000, 1989, 10, 1);
people[1] =newStudent("Maria Morris","computer science");
// print out names and descriptions of all Person objects
for(Personp:people)
System.out.println(p.getName() +", "+p.getDescription());
}
}
packageabstractClasses;
publicclassStudentextendsPerson
{
privateStringmajor;
/**
*@paramnama the student's name
*@parammajor the student's major
*/
publicStudent(Stringname, Stringmajor)
{
// pass n to superclass constructor
super(name);
this.major=major;
}
publicString getDescription()
{
return"a student majoring in "+major;
}
}
测试结果:
测试程序3:
Ÿ编辑、编译、调试运行教材程序5-8、5-9、5-10,结合程序运行结果理解程序(教材174页-177页);
Ÿ掌握Object类的定义及用法;
Ÿ在程序中相关代码处添加新知识的注释。
测试程序:
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)
{
// a quick test to see if the objects are identical
if (this == otherObject) return true;
// must return false if the explicit parameter is null
if (otherObject == null) return false;
// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass()) return false;
// now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// test whether the fields have identical values
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
+ "]";
}
}
packageequals;
/**
* This program demonstrates the equals method.
*@version1.12 2012-01-26
*@authorCayHorstmann
*/
publicclassEqualsTest
{
publicstaticvoidmain(String[]args)
{
Employeealice1=newEmployee("Alice Adams", 75000, 1987, 12, 15);
Employeealice2=alice1;
Employeealice3=newEmployee("Alice Adams", 75000, 1987, 12, 15);
Employeebob=newEmployee("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);
Managercarl=newManager("Carl Cracker", 80000, 1987, 12, 15);
Managerboss=newManager("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());
}
}
packageequals;
publicclassManagerextendsEmployee
{
privatedoublebonus;
publicManager(Stringname,doublesalary,intyear,intmonth,intday)
{
super(name,salary,year,month,day);
bonus= 0;
}
publicdoublegetSalary()
{
doublebaseSalary=super.getSalary();
returnbaseSalary+bonus;
}
publicvoidsetBonus(doublebonus)
{
this.bonus=bonus;
}
publicbooleanequals(ObjectotherObject)
{
if(!super.equals(otherObject))returnfalse;
Managerother= (Manager)otherObject;
// super.equals checked that this and other belong to the same class
returnbonus==other.bonus;
}
publicinthashCode()
{
returnjava.util.Objects.hash(super.hashCode(),bonus);
}
publicString toString()
{
returnsuper.toString() +"[bonus="+bonus+"]";
}
}
测试结果:
测试程序4:
Ÿ在elipse IDE中调试运行程序5-11(教材182页),结合程序运行结果理解程序;
Ÿ掌握ArrayList类的定义及用法;
Ÿ在程序中相关代码处添加新知识的注释。
测试程序:
packagearrayList;
importjava.util.*;
/**
* This program demonstrates the ArrayList class.
*@version1.11 2012-01-26
*@authorCayHorstmann
*/
publicclassArrayListTest
{
publicstaticvoidmain(String[]args)
{
// fill the staff array list with three Employee objects
ArrayList<Employee>staff=newArrayList<>();
staff.add(newEmployee("Carl Cracker", 75000, 1987, 12, 15));
staff.add(newEmployee("Harry Hacker", 50000, 1989, 10, 1));
staff.add(newEmployee("Tony Tester", 40000, 1990, 3, 15));
// raise everyone's salary by 5%
for(Employeee:staff)
e.raiseSalary(5);
// print out information about all Employee objects
for(Employeee:staff)
System.out.println("name="+e.getName() +",salary="+e.getSalary() +",hireDay="
+e.getHireDay());
}
}
packagearrayList;
importjava.time.*;
publicclassEmployee
{
privateStringname;
privatedoublesalary;
privateLocalDatehireDay;
publicEmployee(Stringname,doublesalary,intyear,intmonth,intday)
{
this.name=name;
this.salary=salary;
hireDay= LocalDate.of(year,month,day);
}
publicString getName()
{
returnname;
}
publicdoublegetSalary()
{
returnsalary;
}
publicLocalDate getHireDay()
{
returnhireDay;
}
publicvoidraiseSalary(doublebyPercent)
{
doubleraise=salary*byPercent/ 100;
salary+=raise;
}
}
测试结果:
测试程序5:
Ÿ编辑、编译、调试运行程序5-12(教材189页),结合运行结果理解程序;
Ÿ掌握枚举类的定义及用法;
Ÿ在程序中相关代码处添加新知识的注释。
测试程序:
packageenums;
importjava.util.*;
/**
* This program demonstrates enumerated types.
*@version1.0 2004-05-24
*@authorCayHorstmann
*/
publicclassEnumTest
{
publicstaticvoidmain(String[]args)
{
Scannerin=newScanner(System.in);
System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
Stringinput=in.next().toUpperCase();
Sizesize= 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 _.");
}
}
enumSize
{
SMALL("S"),MEDIUM("M"),LARGE("L"),EXTRA_LARGE("XL");
privateSize(Stringabbreviation) {this.abbreviation=abbreviation; }
publicString getAbbreviation() {returnabbreviation; }
privateStringabbreviation;
}
测试结果:
实验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方法放在哪个类中更合适?
实验程序:
Shape:
packageshape;
abstractclassShape {
abstractdoublegetPerimeter();
abstractdoublegetArea();
}
classRectangleextendsShape{
privateintlength;
privateintwidth;
publicRectangle(intlength,intwidth) {
this.length=length;
this.width=width;
}
doublegetPerimeter(){
return2*(length+width);
}
doublegetArea(){
returnlength*width;
}
}
classCircleextendsShape{
privateintradius;
publicCircle(intradius) {
this.radius=radius;
}
doublegetPerimeter(){
return2 * Math.PI*radius;
}
doublegetArea(){
returnMath.PI*radius*radius;
}
}
Test:
packageshape;
importjava.util.Scanner;
publicclassTest {
publicstaticvoidmain(String[]args) {
Scannerin=newScanner(System.in);
System.out.println("个数");
inta=in.nextInt();
System.out.println("种类");
Stringrect="rect";
Stringcir="cir";
Shape[]num=newShape[a];
for(inti=0;i<a;i++){
Stringinput=in.next();
if(input.equals(rect)) {
System.out.println("长和宽");
intlength=in.nextInt();
intwidth=in.nextInt();
num[i]=newRectangle(width,length);
System.out.println("Rectangle["+"length:"+length+" width:"+width+"]");
}
if(input.equals(cir)) {
System.out.println("半径");
intradius=in.nextInt();
num[i]=newCircle(radius);
System.out.println("Circle["+"radius:"+radius+"]");
}
}
Testc=newTest();
System.out.println("求和");
System.out.println(c.sumAllPerimeter(num));
System.out.println(c.sumAllArea(num));
for(Shapes:num) {
System.out.println(s.getClass()+","+s.getClass().getSuperclass());
}
}
publicdoublesumAllArea(Shapescore[])
{
doublesum=0;
for(inti=0;i<score.length;i++)
sum+=score[i].getArea();
returnsum;
}
publicdoublesumAllPerimeter(Shapescore[])
{
doublesum=0;
for(inti=0;i<score.length;i++)
sum+=score[i].getPerimeter();
returnsum;
}
}
实验结果:
实验3:编程练习2
编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。
实验程序:
package实验3;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.ArrayList;
importjava.util.Scanner;
publicclassID{
privatestaticArrayList<Student>studentlist;
publicstaticvoidmain(String[]args) {
studentlist=newArrayList<>();
Scannerscanner=newScanner(System.in);
Filefile=newFile("C:\\Users\\张季跃\\Desktop\\第六周实验报告\\身份证号.txt");
try{
FileInputStreamfis=newFileInputStream(file);
BufferedReaderin=newBufferedReader(newInputStreamReader(fis));
Stringtemp=null;
while((temp=in.readLine()) !=null) {
Scannerlinescanner=newScanner(temp);
linescanner.useDelimiter(" ");
Stringname=linescanner.next();
Stringnumber=linescanner.next();
Stringsex=linescanner.next();
Stringyear=linescanner.next();
Stringprovince=linescanner.nextLine();
Studentstudent=newStudent();
student.setName(name);
student.setnumber(number);
student.setsex(sex);
student.setyear(year);
student.setprovince(province);
studentlist.add(student);
}
}catch(FileNotFoundExceptione) {
System.out.println("无导入文件");
e.printStackTrace();
}catch(IOExceptione) {
System.out.println("文件出错");
e.printStackTrace();
}
booleanisTrue=true;
while(isTrue) {
System.out.println("请选择你使用的查询方式");
System.out.println("1.姓名查询");
System.out.println("2.身份证号查询");
System.out.println("3.退出");
intnextInt=scanner.nextInt();
switch(nextInt) {
case1:
System.out.println("姓名:");
Stringstudentname=scanner.next();
intnameint=findStudentByname(studentname);
if(nameint!= -1) {
System.out.println(" 姓名:"
+studentlist.get(nameint).getName() +"身份证号:"
+studentlist.get(nameint).getnumber() +" 性别:"
+studentlist.get(nameint).getsex() +" 年龄:"
+studentlist.get(nameint).getyaer()+" 地址:"
+studentlist.get(nameint).getprovince()
);
}else{
System.out.println("查无此人");
}
break;
case2:
System.out.println("身份证号:");
Stringstudentid=scanner.next();
intidint=findStudentByid(studentid);
if(idint!= -1) {
System.out.println(" 姓名:"
+studentlist.get(idint).getName() +" 身份证号:"
+studentlist.get(idint).getnumber() +" 性别:"
+studentlist.get(idint).getsex() +" 年龄:"
+studentlist.get(idint).getyaer()+" 地址:"
+studentlist.get(idint).getprovince()
);
}else{
System.out.println("查无此人");
}
break;
case3:
isTrue=false;
System.out.println("欢迎下次使用!");
break;
default:
System.out.println("输入错误");
}
}
}
publicstaticintfindStudentByname(Stringname) {
intflag= -1;
inta[];
for(inti= 0;i<studentlist.size();i++) {
if(studentlist.get(i).getName().equals(name)) {
flag=i;
}
}
returnflag;
}
publicstaticintfindStudentByid(Stringid) {
intflag= -1;
for(inti= 0;i<studentlist.size();i++) {
if(studentlist.get(i).getnumber().equals(id)) {
flag=i;
}
}
returnflag;
}
}
package实验3;
publicclassStudent{
privateStringname;
privateStringnumber;
privateStringsex;
privateStringyear;
privateStringprovince;
publicString getName() {
returnname;
}
publicvoidsetName(Stringname) {
this.name=name;
}
publicString getnumber() {
returnnumber;
}
publicvoidsetnumber(Stringnumber) {
this.number=number;
}
publicString getsex() {
returnsex;
}
publicvoidsetsex(Stringsex) {
this.sex=sex;
}
publicString getyaer() {
returnyear;
}
publicvoidsetyear(Stringyear) {
this.year=year;
}
publicString getprovince() {
returnprovince;
}
publicvoidsetprovince(Stringprovince) {
this.province=province;
}
}
实验结果:
第三部分:实验总结:
在本周的学习中,我对继承有了初步的了解,知道了它的优点和缺点,并对继承的简单应用有了初步的掌握。
但尽管有老师的讲解和助教的指导,而且我在十一也有过学习,但我对于继承在实际中的应用还是十分不熟练,特别是在本次的实验中关于实验二和实验三继承部分的应用让我伤透了脑筋,自己编写的程序总是运行不过去,到最后只好参考一下其他同学,即使如此,也有搞不懂的地方,只好到学校后再请教同学。
优质内容筛选与推荐>>