zoukankan      html  css  js  c++  java
  • 动手动脑四



    1.动手实验:继承条件下的构造方法调用
    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调用基类构造方法,必须是子类构造方法中的第一个语句。子类的构造方法在运行之前,必须调用父类的构造方法。因为子类必须继承父类的变量和方法。如果不先给父类中的变量赋值,则子类中从父类继承的变量没有赋值。所以不能反过来先给子类赋值。所以super的构造语句必须放在前面。

    2..在子类中,若要调用父类中被覆盖的方法,可以使用super关键

    class fu
    {
        public void A()
         {
                System.out.println("Parent ");
              }
    }
    class zi extends fu
    {
        public void A()
         {
            super.A();
            System.out.println("Child ");
          }
    }
    public class Test {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
                        zi c = new zi();
                        c.A();
        }
    }

    结论:

     Java“方法覆盖”的语法规则

    (1)覆盖方法的允许访问范围不能小于原方法。

    (2)覆盖方法所抛出的异常不能比原方法更多。

    (3)声明为final方法不允许覆盖。

    (4)不能覆盖静态方法。

    3.下列语句哪一个将引起编译错误?为什么?哪一个会引起运行时错误?为什么?

    m=d;

    d=m;

    d=(Dog)m;

    d=c;

    c=(Cat)m;

    结论:第二句和第四句会出错

    原因:父类不可直接给子类赋值,子类可以直接给父类赋值,同为子类不能相互赋值,父类可强制类型转换给子类赋值

    4.

  • 相关阅读:
    【一天一道兼容性】之——IE6下fixed失效
    【前端重构技能天赋】(三)——最终篇
    Putty中文乱码问题
    Cygwin Application initialization failed: no display name and no $DISPLAY environment
    c++中的string用法(二)
    在win7下面使用cygwin,并且安装使用git,以及git简明教程
    vi 一些命令(备忘,自己用的)
    对C++中string类型的总结
    ofstream和ifstream详细用法
    写第一个shell脚本,遇到的问题总结整理。
  • 原文地址:https://www.cnblogs.com/love-nan/p/9928383.html
Copyright © 2011-2022 走看看