java第四次作业

《Java技术》第四次作业

(一)学习总结

1.学习使用思维导图对Java面向对象编程的知识点(封装、继承和多态)进行总结。
2.阅读下面程序,分析是否能编译通过?如果不能,说明原因。应该如何修改?程序的运行结果是什么?为什么子类的构造方法在运行之前,必须调用父 类的构造方法?能不能反过来?

class Grandparent {
    public Grandparent() {
        System.out.println("GrandParent Created.");
    }
    public Grandparent(String string) {
        System.out.println("GrandParent Created.String:" + string);
    }
}
class Parent extends Grandparent {
    public Parent() {        
        System.out.println("Parent Created");
        super("Hello.Grandparent.");
    }
}
class Child extends Parent {
    public Child() {
        System.out.println("Child Created");
    }
}
public class Test{
    public static void main(String args[]) {
        Child c = new Child();
    }
}

编译错误:构造方法调用应该放在第一句。
3 . 阅读下面程序,分析程序中存在哪些错误,说明原因,应如何改正?正确程序的运行结果是什么?

class Animal{
  void shout(){
      System.out.println("动物叫!");
  }
}
class Dog extends Animal{
      public void shout(){  
          System.out.println("汪汪......!");  
     }
      public void sleep() {
       System.out.println("狗狗睡觉......");
      } 
}
public class Test{
    public static void main(String args[]) {
        Animal animal = new Dog(); 
        animal.shout();
        animal.sleep();
        Dog dog = animal;
        dog.sleep(); 
        Animal animal2 = new Animal();
        dog = (Dog)animal2;
        dog.shout();
    }
}

Dog dog = animal;向下转型错误。
if(animal2 instanceof Dog){
dog = (Dog)animal2;
dog.shout();
}
向下转型用instanceof;
4.运行下列程序

class Person { 
   private String name ; 
   private int age ; 
   public Person(String name,int age){ 
         this.name = name ; 
         this.age = age ; 
   } 
}
public class Test{  
      public static void main(String args[]){ 
             Person per = new Person("张三",20) ; 
             System.out.println(per);
             System.out.println(per.toString()) ; 
  } 
}

(1)程序的运行结果如下,说明什么问题?

Person@166afb3
Person@166afb3

系统自动调用Object类的toString方法。
(2)那么,程序的运行结果到底是什么呢?利用eclipse打开println(per)方法的源码,查看该方法中又调用了哪些方法,能否解释本例的运行结果?

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

(3)在Person类中增加如下方法

public String toString(){ 
    return "姓名:" + this.name + ",年龄:" + this.age ; 
} 

姓名:张三,年龄:20

姓名:张三,年龄:20
输出对象时调用的是被子类覆写过的toString()方法。

(二)实验总结

1.员工信息

  • 程序设计思路:
    建父类员工类,定义父类的属性,并设置toString()方法;
    建子类管理层类和职员类,使其继承父类,用super关键字指定调用父类中的构造方法,并定义子类自己的属性;
    测试类,调用覆写过的方法toString()。

2.图形

  • 程序设计思路:
    (1)建一个平面图形抽象类和一个立体图形抽象类,并且在各自类中定义抽象方法面积和周长,体积和表面积;
    (2)建球类、圆柱类,圆锥类、矩形类、三角形类、圆类,分别在类中定义属性,继承抽象类,覆写全部抽象方法;
    (3)测试类,分别实例化子类对象,调用被子类覆写过的方法。

(三)代码托管

  • 码云commit历史截图
posted @ 2017-04-18 10:28  一块二  阅读(179)  评论(0编辑  收藏  举报