【问题标题】:How to write a default constructor in Java that contains a custom class as a parameter如何在 Java 中编写包含自定义类作为参数的默认构造函数
【发布时间】:2020-12-03 18:36:19
【问题描述】:

我正在尝试为大学课程编写程序,但我被困在构造函数上。我的教授希望我们使用“this”作为默认构造函数,但我不知道如何编写第三个实例。我附上了相关的代码。 Person 类是我在另一个 src 文件中定义的类。

public class Vehicle {
private String manufacturer;
private int cylinders;
private Person owner;

public void setManufacturer (String mf) { manufacturer = new String (mf); }
public String getManufacturer () { return new String (manufacturer); }
public void setCylinders (int c) { cylinders = c; }
public int getCylinders () { return cylinders; }
public void setOwner (Person own) { owner = new Person (own); }
public Person getOwner () { return new Person (owner); }

public Vehicle () {     //constructor
    this ("",0, ???);  //this is the line where I get the error
}

这里是被引用的 Person 类:

// ---------------------------------------------------
//                    Person.java
// ---------------------------------------------------

public class Person {
    // Instance Variables/Data

    private StringBuffer firstName;         // Person's First Name
    private StringBuffer lastName;          // Person's Last Name
    private int age;                        // Person's Age
    private String ssn;                     // Person's Social Security Number
    private static int population;          // Number of Person objects
    private boolean finalizeNotCalled;      // Flag to prevent multiple finalize executes

    // Class Behaviors -- Getters and Setters

    public void         setFirstName ( String fn ) { firstName = new StringBuffer( fn ); }
    public StringBuffer getFirstName( )            { return new StringBuffer( firstName.toString()); }
    public void         setLastName ( String ln )  { lastName = new StringBuffer( ln ); }
    public StringBuffer getLastName( )             { return new StringBuffer( lastName.toString()); }
    public void         setAge ( int a )           { age = a; }
    public int          getAge ( )                 { return age; }
    public void         setSsn ( String s )        { ssn = s; }
    public String       getSsn ( )                 { return ssn; }
    public static int   getPopulation ( )          { return population; }

    public Person ( ) {
        this ( " ", " ", 0, " ");
        System.out.println( "Person - default, no-arg constructor ");
    }

    public Person ( String fn, String ln, int a, String s ) {
        firstName = new StringBuffer( fn );
        lastName  = new StringBuffer( ln );
        age = a;
        ssn = s;
        population++;
        finalizeNotCalled = true;
        System.out.println( "Person - Overloaded 4-arg constructor ");
    }

    public Person ( String fn, String ln ) {
        // Some comment
        this ( fn, ln, 0, " ");
        System.out.println( "Person - Overloaded 2-arg constructor ");
    }

    public Person ( Person original ) throws NullPointerException {

        if ( original == null )
            throw new NullPointerException( "null argument passed to Person copy constructor" );

        firstName = new StringBuffer( original.firstName.toString());
        lastName  = new StringBuffer( original.lastName.toString() );
        age = original.age;
        ssn = "999-45-6789";
        population++;
        finalizeNotCalled = true;
        System.out.println( "Person - copy constructor ");
    }

    public Person clone ( ) {
        return new Person(this);
    }

    static {
        population = 0;
        System.out.println("Person - Static initializer block.");
    }

    @Override
    public String toString ( ) {
        String x;
        x = " " + firstName + " " + lastName + " " + age +
                " " + ssn + " " + population + " ";
        return x;
    }

    @Override
    public boolean equals ( Object obj ) {
        if ( this == obj ) return true;
        if ( obj == null ) return false;
        if ( getClass() != obj.getClass() ) return false;

        Person d = (Person) obj;   // Creating a copy of the reference, not an object

        if ( firstName.toString().equals ( d.firstName.toString()) &&
                lastName.toString(). equals ( d.lastName.toString())  &&
                age == d.age  &&
                finalizeNotCalled == d.finalizeNotCalled )
        {
            return true;
        }
        else
            return false;
    }

    @Override
    public void finalize ( ) {
        if ( finalizeNotCalled ) {
            population--;
            finalizeNotCalled = false;
            System.out.println ( "Person - finalize method - " + toString() );
        }
    }
}

【问题讨论】:

  • 您不能同时使用super()this()。任选其一。
  • 在构造函数中调用this(...) 用于调用该类的另一个构造函数。你的类甚至有一个接受 3 个参数的构造函数吗?如果是,那么您应该将其添加到您的问题中,因为您要么尝试调用不存在的构造函数,要么尝试调用我们不知道的构造函数,因此无法告诉您如何调用它。
  • 删除了 super();但我仍然不知道如何填写“this”。
  • 我已将 Person 类添加到原始问题中。

标签: java class constructor this


【解决方案1】:

super()this(...) 不能一起使用。我认为你需要这样的东西:

    ...

    // Default no-arg constructor
    // Calls the other constructor, supplying default values
    public Vehicle() {
        this("", 0, new Person());
    }

    public Vehicle(String manufacturer, int cylinders, Person owner) {
        this.manufacturer = manufacturer;
        this.cylinders = cylinders;
        this.person = person;
    }

    ...

祝你好运!

【讨论】:

    【解决方案2】:

    this(...) 必须是构造函数的第一条语句,去掉 super();

    并且 this(...) 正在调用具有给定参数的构造函数。

    例子:

    public Vehicule() {
      this("default manufacturer"); // call Vehicule(String manufacturer)
    }
    
    public Vehicule(String manufacturer) {
      this.manufacturer = manufacturer;
    }
    

    【讨论】:

    • 那你什么时候使用 super() 呢?我还必须为扩展车辆类的类创建构造函数。那我会用吗?
    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2021-04-27
    • 2020-09-04
    • 2016-06-05
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多