当前位置: 移动技术网 > IT编程>开发语言>Java > Java中自动生成构造方法详解

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网