2019/10/21 动手动脑

 第一次结果:

   子类在创建是,先调用父类的构造函数,然后再调用自身的构造函数。

第二次结果:

  如果显示调用父类构造函数(super),则必须放在子类构造函数第一行,否则会报错

完整代码:

package com.javaclass4;

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();
    
  }

}

   答案肯定是不能的,因为构造函数是对类进行初始化的,子类继承了父类数据,所以必须要父类对数据进行初始化,所以必须先调用父类的构造函数,然后再调用子类的构造函数。

  原因是在“+”运算中,当任何一个对象与一个String对象连接时,会隐式地调用其toString()方法,默认情况下,此方法返回“类名 @ + hashCode”。为了返回有意义的信息,子类可以重写toString()方法 

 这是重写的toString()方法

 代码:

输出结果:

可以用super关键字调用父类的方法。 输出结果:

Java方法的覆盖原则:

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

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

(3)声明为final方法不允许覆盖。 例如,Object的getClass()方法不能覆盖。

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

 

猜你喜欢

转载自www.cnblogs.com/yangxiao-/p/11728725.html