一 点睛
1 如果一个类没有定义任何构造函数,那么该类会自动生成1个默认的构造函数。默认构造函数没有参数。
2 如果一个类定义了构造函数,但这些构造函数都有参数,那么不会生成默认构造函数,也就是说此时类没有无参的构造函数。
通过两个例子来说明。
二 使用无参构造函数的错误
1 代码
- public class ConstructWithNoPara
- {
- public static void main( String[] args )
- {
- Person p = new Person(); // 此行有错误,没有不含参数的构造函数
- p.talk();
- }
- }
- class Person
- {
- private String name;
- private int age;
- public Person( int age )
- {
- name = 'Yuhong';
- this.age = age;
- }
- public Person( String name, int age )
- {
- this.name = name;
- this.age = age;
- }
- public void talk()
- {
- System.out.println( '我叫:' + name + ' 我今年:' + age + '岁' );
- }
- }
2 运行
- Exception in thread 'main' java.lang.Error: Unresolved compilation problem:
- The constructor Person() is undefined
- at ConstructWithNoPara.main(ConstructWithNoPara.java:18)
三 正确使用无参构造函数
1 代码
- public class ConstructOverload
- {
- public static void main( String[] args )
- {
- Person p = new Person();
- p.talk();
- }
- }
- class Person
- {
- private String name;
- private int age;
- public Person()
- {
- name = 'cakin';
- age = 22;
- }
- public Person( int age )
- {
- name = 'kehr';
- this.age = age;
- }
- public Person( String name, int age )
- {
- this.name = name;
- this.age = age;
- }
- public void talk()
- {
- System.out.println( '我叫:' + name + ' 我今年:' + age + '岁' );
- }
- }
2 运行
我叫:cakin 我今年:22岁
联系客服