您的位置:首页 > 编程语言 > Java开发

Java中 每个类在没有声明构造方法的前提下,会自动生成一个不带参数的构造方法

2011-08-25 14:10 381 查看

每个类在没有声明构造方法的前提下,会自动生成一个不带参数的构造方法,如果类一但声明有构造方法,就不会产生了.证明如下:

例1:

class person
{
person(){System.out.println("父类-person");}
person(int z){}
}
class student extends person
{
//	student(int x ,int y){super(8);}
}

class Rt
{
public static void main(String[]args)
{
student student_dx=new student();//创建student类的对象
}
}
//输出结果:父类-person

例2:
class person
{
person(){System.out.println("父类-person");}
person(int z){}
}
class student extends person
{
student(int x ,int y){super(8);}
}

class Rt
{
public static void main(String[]args)
{
student student_dx=new student(3,4);//创建student类的对象
}
}
//没有输出结果


例1说明:student类自动生成student() {super();}(前提是:student类没有声明构造方法的前提下) 'super()'是用来调用父类的构造方法.

例2中的person()方法没有被调用,说明student类没有产生student(){super();}方法.这是因为student类已经声明构造方法,默认的那个不带参数的构造方法就不产生了.

再举例:

class person
{
person(int z){}
}
class student extends person
{

}

class Rt
{
public static void main(String[]args)
{
student student_dx=new student();//创建student类的对象
}
}
/*报错:
exercise14.java:8: 找不到符号
符号: 构造函数 person()
位置: 类 person
class student extends person
^
1 错误
*/

说明:student类自动产生了一个student(){super();},但是由于person类已经声明了构造方法,默认的那个带参数的构造方法没有产生.,所以报错中提到找不到构造函数person()



[align=center] [/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐