Java中自动生成构造方法详解
时间:2021-06-24 08:19:29|栏目: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()
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
上一篇:当面试官问我ArrayList和LinkedList哪个更占空间时,我是这么答的(面试官必问)
栏 目:JAVA代码
本文标题:Java中自动生成构造方法详解
本文地址:http://www.codeinn.net/misctech/147338.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




