您现在的位置: 中国教师站 >> 教师关注 >> 电脑技术 >> 编程技术 >> Java >> 正文

Google
调用构造函数创建对象时应该知道的两点
作者:Siny 文章来源:中国教师站cn-teacher 点击数: 更新时间:2007-4-22 13:21:29

一、有父类的类在创建自己对象时,先调用父类的构造函数,有以下两种情况:



    1、当父类没有构造器时(即只有默认的隐式的无参构造器),先调用该隐式构造器,再调用自己的构造器;



public class test extends sup{
  public test() {
  }
  public test(int i){
    System.out.println(i);
  }
  public static void main(String args[]) {
    test t = new test(1);
  }
}
class sup{
}



    注意:要么父类无任何显式构造器,要么父类必须声明显式的无参构造器,二者必居其一!父类有其它构造器--有参构造器,但没有无参构造器时,会出现编译期错误。



    2、当父类有显式构造器时--指显式声明了无参构造器,先调用该无参构造器,再调用自己构造器。



public class test extends sup{
  public test() {
  }
  public test(int i){
    System.out.println(i);
  }
  public static void main(String args[]) {
    test t = new test(1);
  }
}
class sup{
 public sup(){//---------调用该构造器
   System.out.println(3);
 }
 public sup(int i){
   System.out.println(4);
 }
}


二、无父类的类在创建自己对象时,直接调用自己的构造器,无须调用自己的无参构造器。



public class test{
  public test(int i){
    System.out.println(i);
  }
  public static void main(String args[]) {
    test t = new test(1);
  }
}

相关专题:
 
 网友评论:(评论内容只代表网友观点,与本站立场无关!)
GOOGLE广告

阅读排行

| 设为首页 | 加入收藏 | 联系站长 | 友情链接 | 版权申明 |
中国教师站

中国教师站 版权所有 Copyright © 2006-2020 All Rights Reserved 站长:Sina & Siny
[备用域名:www.JXZYW.Com] 有事请留言有事请留言
【实力成就精品 诚信呵护品牌】

信息产业部备案
苏ICP备06018635号