打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java的无参构造函数

一 点睛

1 如果一个类没有定义任何构造函数,那么该类会自动生成1个默认的构造函数。默认构造函数没有参数。

2 如果一个类定义了构造函数,但这些构造函数都有参数,那么不会生成默认构造函数,也就是说此时类没有无参的构造函数。

通过两个例子来说明。

二 使用无参构造函数的错误

1 代码

  1. public class ConstructWithNoPara
  2. {
  3. public static void main( String[] args )
  4. {
  5. Person p = new Person(); // 此行有错误,没有不含参数的构造函数
  6. p.talk();
  7. }
  8. }
  9. class Person
  10. {
  11. private String name;
  12. private int age;
  13. public Person( int age )
  14. {
  15. name = 'Yuhong';
  16. this.age = age;
  17. }
  18. public Person( String name, int age )
  19. {
  20. this.name = name;
  21. this.age = age;
  22. }
  23. public void talk()
  24. {
  25. System.out.println( '我叫:' + name + ' 我今年:' + age + '岁' );
  26. }
  27. }

2 运行

  1. Exception in thread 'main' java.lang.Error: Unresolved compilation problem:
  2. The constructor Person() is undefined
  3. at ConstructWithNoPara.main(ConstructWithNoPara.java:18)

三 正确使用无参构造函数

1 代码

  1. public class ConstructOverload
  2. {
  3. public static void main( String[] args )
  4. {
  5. Person p = new Person();
  6. p.talk();
  7. }
  8. }
  9. class Person
  10. {
  11. private String name;
  12. private int age;
  13. public Person()
  14. {
  15. name = 'cakin';
  16. age = 22;
  17. }
  18. public Person( int age )
  19. {
  20. name = 'kehr';
  21. this.age = age;
  22. }
  23. public Person( String name, int age )
  24. {
  25. this.name = name;
  26. this.age = age;
  27. }
  28. public void talk()
  29. {
  30. System.out.println( '我叫:' + name + ' 我今年:' + age + '岁' );
  31. }
  32. }

2 运行

我叫:cakin  我今年:22岁
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
java 必须用this的几种情况
反射概述及demo
java之反射
Java学习笔记:详解this关键字
IEnumerable和IEnumerable<T>接口
[你必须知道的.NET] 第四回:后来居上:class和struct
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服