软件编程
位置:首页>> 软件编程>> java编程>> Java中自动生成构造方法详解

Java中自动生成构造方法详解

作者:StellaAh  发布时间:2023-06-21 14:17:44 

标签:Java,自动生成,构造方法

Java中自动生成构造方法详解

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

例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()

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com