构造器的特征

  • 它具有与类相同的名称
  • 它不声明返回值类型(与声明为void不同)
  • 不能被static、final、synchronized、abstract、native修饰,不能有return语句返回值

构造器的作用

  • 创建对象并给对象进行初始化

例如:

  1. public class Demo {
  2. public static void main(String[] args) {
  3. // 创建类的对象: new + 构造器
  4. Person people = new Person();
  5. people.eat();
  6. }
  7. }
  8. class Person{
  9. // 属性
  10. String name;
  11. int age;
  12. // 构造器 1
  13. public Person(){
  14. System.out.println("定义构造器");
  15. }
  16. // 构造器 2
  17. // 初始化对象
  18. public Person(String name){
  19. this.name = name;
  20. }
  21. // 方法
  22. public void eat(){
  23. System.out.println("eating");
  24. }
  25. }
  1. <br />