【问题标题】:how to create instance of a object without passing argument in constructor?如何在构造函数中不传递参数的情况下创建对象的实例?
【发布时间】:2015-07-08 05:56:57
【问题描述】:

我有一个 Student 类,它有构造函数 Student(int id, string name)

现在,我想在不触及构造函数的情况下创建 Student Class 的对象。我该怎么做?

点赞Student std = new Student();

不是Student std = new Student(1, "Benjamin");

【问题讨论】:

    标签: java constructor instance


    【解决方案1】:

    创建default constructor,点赞

    Student();
    

    在Java 中,默认构造函数 指的是nullary constructor,如果没有为类定义构造函数,编译器会自动生成该nullary constructor。默认构造函数隐式调用超类的空构造函数,然后执行一个空的主体。也可以自己写。

    请注意,根据您的编码设计和要求,可以有许多构造函数。说,

    class Student {  
    
        // default constructor
        public Student() {}
    
        // one param constructor
        public Student(int id) {
            this.id = id;
        }
    
        // two param constructor
        public Student(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }
    

    如果你有默认构造函数,那么没有

    Student std = new Student(1, "Benjamin");
    

    您可以创建一个std 对象,例如:

    Student std = new Student();
    

    【讨论】:

      【解决方案2】:

      您必须创建一个无参数构造函数 - Student()。如果你没有 Student(int id, string name) 构造函数,编译器会自动创建一个空的无参数构造函数。

      【讨论】:

      • 没有其他选择吗?
      【解决方案3】:

      你应该在你的类中创建第二个没有参数的构造函数(所谓的“默认构造函数”):

      class Student {
          int id;
          String name;
      
          // new constructor
          public Student() {
          }
      
          // old constructor: we don't change it.
          public Student(int id, String name) {
              this.id = id;
              this.name = name;
          }
      }
      

      【讨论】:

        【解决方案4】:

        你必须添加一个没有参数的构造函数。

        请注意,这只是一个仅用于学术目的的解决方案:如果您不喜欢创建不带参数的新构造函数,还有另一种可能性。删除带参数的构造函数,如果你这样做会自动将不带参数的默认构造函数添加到你的类中。显然,如果您这样做,您必须更改现有代码,用不带参数的新调用替换对参数化构造函数的旧调用!

        【讨论】:

          【解决方案5】:

          你可以这样做;前提是您的类具有默认的空构造函数和 setter 方法:

          Student st = new Student();
          st.setId(1);
          .
          ..
          

          【讨论】:

            【解决方案6】:

            我有同样的问题,虽然应该自动实现的默认构造函数应该允许没有参数的对象。错误状态:无法解析构造函数。 :(

            User user = new User();
            user.setUsername(registerRequest.getUsername());
            user.setPassword(registerRequest.getPassword());
            user.setEmail(registerRequest.getEmail());
            

            所以用户();需要参数,我不能对用户应用所有其他代码行

            【讨论】:

              猜你喜欢
              • 2019-03-27
              • 1970-01-01
              • 2020-07-25
              • 1970-01-01
              • 2023-03-10
              • 1970-01-01
              • 2017-01-05
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多