1.阅读下面程序,分析是否能编译通过?如果不能,说明原因。应该如何修改?程序的运行结果是什么?为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?
classGrandparent{publicGrandparent(){System.out.println("GrandParentCreated.");}publicGrandparent(Stringstring){System.out.println("GrandParentCreated.String:"+string);}}classParentextendsGrandparent{publicParent(){System.out.println("ParentCreated");super("Hello.Grandparent.");}}classChildextendsParent{publicChild(){System.out.println("ChildCreated");}}publicclassTest{publicstaticvoidmain(Stringargs[]){Childc=newChild();}}不能,super调用父类中指定构造方法的操作,语句必须放在子类构造方法的是首行。将super移至system上边,子类继承父类的属性和方法,同时也可以修改父类的属性或重写父类的方法,以及在父类的基础上添加新的属性和方法。因此,父类和子类之间反映的是“一般与特殊”的关系。(能不能反过来?)--不能,父类根本不知道子类有什么变量,而且这样一来子类也得不到初始化的父类变量,导致程序运行出错
2.阅读下面程序,分析程序中存在哪些错误,说明原因,应如何改正?正确程序的运行结果是什么?
classAnimal{voidshout(){System.out.println("动物叫!");}}classDogextendsAnimal{publicvoidshout(){System.out.println("汪汪......!");}publicvoidsleep(){System.out.println("狗狗睡觉......");}}publicclassTest{publicstaticvoidmain(Stringargs[]){Animalanimal=newDog();animal.shout();animal.sleep();Dogdog=animal;dog.sleep();Animalanimal2=newAnimal();dog=(Dog)animal2;dog.shout();}}测试类中animal.sleep();有错animal是向上转型的只能用继承和重写不能用子类新定义的。Dogdog=animal;向下转型出错格式:子类名称子类对象=(子类)父类实例;dog=(Dog)animal2;dog.shout();父类引用的对象是父类本身,那么在向下转型的过程中是不安全的,编译不会出错,但是运行时会出现java.lang.ClassCastException错误。它可以使用instanceof来避免出错此类错误。
3.运行下列程序
classPerson{privateStringname;privateintage;publicPerson(Stringname,intage){this.name=name;this.age=age;}}publicclassTest{publicstaticvoidmain(Stringargs[]){Personper=newPerson("张三",20);System.out.println(per);System.out.println(per.toString());}}(1)程序的运行结果如下,说明什么问题?
Person@166afb3Person@166afb3(2)那么,程序的运行结果到底是什么呢?利用eclipse打开println(per)方法的源码,查看该方法中又调用了哪些方法,能否解释本例的运行结果?(3)在Person类中增加如下方法
publicStringtoString(){return"姓名:"+this.name+",年龄:"+this.age;}重新运行程序,程序的执行结果是什么?说明什么问题?
1).不管有没有tostring都没有把数传进去;2).源码
publicvoidprintln(Objectx){Strings=String.valueOf(x);synchronized(this){print(s);newLine();}}结果张三20;3).用户自己写的tostring方法系统调用默认的头string方法,所以会出来hash码如果用户写了tostring方法了,就覆写了object类中的tostring方法,这样出来的结果是张三20;4.汽车租赁公司,出租汽车种类有客车、货车和皮卡三种,每辆汽车除了具有编号、名称、租金三个基本属性之外,客车有载客量,货车有载货量,皮卡则同时具有载客量和载货量。用面向对象编程思想分析上述问题,将其表示成合适的类、抽象类或接口,说明设计思路。现在要创建一个可租车列表,应当如何创建?
定义一个汽车类的接口方法getNo(编号的),getName(名称的),getMoney(租金的)在定义一个载客量的接口,方法只有一个就是载客量,在定义一个载货量的接口,方法只有一个就是载货量,客车实现汽车和载客量的接口,货车实现汽车和载货量的接口,皮卡实现汽车载客量载货量三个接口。
5.阅读下面程序,分析代码是否能编译通过,如果不能,说明原因,并进行改正。如果能,列出运行结果
interfaceAnimal{voidbreathe();voidrun();voideat();}classDogimplementsAnimal{publicvoidbreathe(){System.out.println("I'mbreathing");}publicvoideat(){System.out.println("I'meating");} publicvoidrun(){ System.out.println("I'mrunning"); }}publicclassText{publicstaticvoidmain(String[]args){Dogdog=newDog();dog.breathe();dog.eat();}}(二)实验总结1.银行新用户现金业务办理
2.公司本题和实验三的第四题差不多,只是多了一个继承,要注意的是,管理层继承了员工类,在管理层的构造方法中要把super关键字写在首行,且括号里写父类的属性