• java课后思考问题(七)


    1.继承条件下的构造方法调用

    package parent;
    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()
      {
      //super("Hello.Grandparent.");
      System.out.println("Parent Created");
      //super("Hello.Grandparent.");
      }
    }
    class Child extends Parent
    {
      public Child()
      {
        System.out.println("Child Created");
      }
    }
    public class TestInherits
    {
      public static void main(String args[])
      {
        Child c = new Child();
      }
    }

    结论:通过super调用基类构造方法,必须是子类构造方法中的第一个语句。也就是说,子类的构造方法在运行之前,必须调用父类的构造方法。因为子类必须继承父类的变量和方法。如果不先给父类中的变量赋值,则子类中从父类继承的变量没有赋值。所以不能反过来先给父类赋值。

    2.类型转换

    下列语句哪一个将引起编译错误?为什么?哪一个会引起运行时错误?为什么? m=d; d=m; d=(Dog)m; d=c; c=(Cat)m; 先进行自我判断,得出结论后,运行TestCast.java实例代码,看看你的判断是否正确。

            d=m,d=c运行时将会报错。因为m是父类对象,d是子类对象。将父类对象转化成子类对象,必须进行强制转换。而d和c是两个互不相干的类对象,所以不能将d赋值给c.

    3.子类父类拥有同名的方法

    1. 左边的程序运行结果是什么? 2. 你如何解释会得到这样的输出? 3. 计算机是不会出错的,之所以得 到这样的运行结果也是有原因的, 那么从这些运行结果中,你能总 结出Java的哪些语法特性?

    public class ParentChildTest {
    public static void main(String[] args) {
    Parent parent=new Parent();
    parent.printValue();
    Child child=new Child();
    child.printValue();

    parent=child;
    parent.printValue();

    parent.myValue++;
    parent.printValue();

    ((Child)parent).myValue++;
    parent.printValue();

    }
    }

    class Parent{
    public int myValue=100;
    public void printValue() {
    System.out.println("Parent.printValue(),myValue="+myValue);
    }
    }
    class Child extends Parent{
    public int myValue=200;
    public void printValue() {
    System.out.println("Child.printValue(),myValue="+myValue);
    }
    }

    结论:

    (1)子类对象可以赋值给父类的对象。父类进行子类强制转换可以赋值给子类的对象。

    (2)子类能覆盖父类,但是父类中的变量的值是不改变的,访问父类中的变量时可用super来访问,反之则一直被子类覆盖。父类被覆盖时,对父类中的变量进行操作时,父类中的变量改变,但输出时仍输出覆盖父类的子类的变量。

    (3)(child)Parent.myValue++,这时改变的将是覆盖父类的子类。

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    记一次对网站的SEO优化改造
    pc端页面添加响应式布局
    linux开启coredump
    vue中鼠标事件
    垂直居中的几种方法
    最准确的身份证号码正则验证
    将数组[NaN ,1,21,32,NaN,41,5]里面的NaN成员剔除(复用underscore.js的filter方法)
    项目中使用Mockjs模拟数据
    研究生学习与生活(2019)
    研究生学习与生活(九)
  • 原文地址:https://www.cnblogs.com/wl2017/p/7809978.html
Copyright © 2020-2023  润新知