zoukankan      html  css  js  c++  java
  • Constructor call must be the first statement in a constructor


    super()和this ()不能共存。否则编译时会报异常。

    Constructorcall must be the first statement in a constructor

    换句话说就是super()和this()都必须在构造方法的第一行。

    this(有參数/无參数) 用于调用本类对应的构造函数

    super(有參数/无參数) 用于调用父类对应的构造函数

    并且在构造函数中,调用必须写在构造函数定义的第一行,不能在构造函数的后面使用。

    一个构造函数定义中不能同一时候包含this调用和super调用,假设想同一时候包含的话,能够在this()调用的那个构造函数中首先进行super()调用。也能够把TestB()这种方法改动成非构造方法。在构造方法TestB(int i)中调用。

    正确解释:The parent class' constructor needs to becalled before the subclass' constructor. This will ensure that if you call anymethods on the parent class in your constructor, the parent class has alreadybeen set up correctly.

    翻译:之前父类的构造函数须要调用子类的构造函数。

    这将确保假设你调用不论什么方法在父类构造函数,父类已经被正确设置。


    2.错误:Implicit super constructor xx() is undefined for default constructor. Must define an explicit constructor 


     由于你的父类已经定义了一个有參的构造函数,此时编译器不会为你调用默认的构造函数。
    当子类继承时,必须在自己的构造函数显式调用父类的构造函数。自己才干确保子类在初始化前父类会被实例化,
    假设你父类中有无參的构造函数,子类就不会强制要求调用。即你写的那个就能够通过,
    编译器会默认帮你调用父类的构造函数。 
    按原来的思路,必须该成以下的:  

    class Person { 
    	protected String name; 
    	protected int age; 
    	//你已经定义了自己主动的构造函数,此时编译器不会为你创建默认的构造函数 
    	public Person(String name,int age) { 
    		this.name=name; 
    		this.age=age; 
    	} 
    	public void print() { 
    		System.out.println("Name:"+name+"/nAge:"+age); 
    	}
    } 
    /*由于父类的构造函数是有參的,所以编译不会为你自己主动调用默认的构造函数。此时。子类在自己的构造函数中必须显式的调用父类的构造函数 */
    class Student extends Person { 
    	public Student(){      //子类构造函数 
    	//super();   不行,由于你的父类没有无參的构造函数 
    	
    	super("a",1); 
          //显示调用父类的构造函数。并且必须是第一行调用 
    	} 
    } 
    	class Test { 
    		public static void main(String args[]){ 
    		} 
    }



  • 相关阅读:
    Runtime Type Information 运行时类型信息RTTI
    ADO实现单条记录的刷新
    TDataLink类说明
    编程实现文件关联
    咏南的连接池
    关系数据库系统PK面向对象数据库系统
    div+CSS编程技巧
    Hadoop编程笔记(一):Mapper及Reducer类详解
    如何统计博客园的个人博客访问量
    MapReduce编程模型:用MapReduce进行大数据分析
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6926038.html
Copyright © 2011-2022 走看看