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.

  • 相关阅读:
    用wamp配置的环境,想用CMD连接mysql怎么连
    Mysql删除表
    MySQL创建表
    Leetcode 130. Surrounded Regions
    Leetcode 111. Minimum Depth of Binary Tree
    Leetcode 110. Balanced Binary Tree
    Leetcode 98. Validate Binary Search Tree
    Leetcode 99. Recover Binary Search Tree
    Leetcode 108. Convert Sorted Array to Binary Search Tree
    Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
  • 原文地址:https://www.cnblogs.com/love-nan/p/9928383.html
Copyright © 2011-2022 走看看