简体   繁体   中英

How do I create a public default constructor and an overloaded constructor?

I am extremely new to Java and coding in general. I am working on a project where I have created two interfaces and am now creating a concrete class named VehicleChassis that implements my Chassis interface. First, I created a String named chassisName instance variable. Now, I need to create a default constructor and overloaded constructor with the following value - A String with a parameter value of chassisName. I have searched the Internet on how to do both, but I am so confused. Help!

Below is the code I have so far.

public abstract class VehicleChassis implements Chassis{
public String chassisName;
}

You mean this?

public abstract class VehicleChassis implements Chassis{
    public String chassisName;
    VehicleChassis() {
        chassisName = "name";
    }
    VehicleChassis(final String chassisName) {
        this.chassisName = chassisName;
    }
}

You won't be able to instantiate this VehicleChassis because you've declared it as abstract. You can use the constructors if you extend this class, though. Consider declaring the constructors protected if that's what you intend to do.

If you arre not implement all the methods in Chassis keep VehicleChassis as abstract .

You can overload constructor as many as you want.

public String chassisName;
public VehicleChassis() {
    chassisName = "No";
}
public VehicleChassis(String chassisName) {
    this.chassisName = chassisName;
}

If you have another instance variable:

public VehicleChassis(String chassisName, int price) {
    this.chassisName = chassisName;
    this.price = price;
}

For more about constructor overloading read this question answer .

You can create constructor as below.If the instance variable is more and all are not mandatory then you can use builder pattern to build your object step by step.

 public class VehicleChassis implements Chassis {
        public String chassisName;

        public VehicleChassis() {
            // some code
        }

        public VehicleChassis(String chassisName) {
            this.chassisName = chassisName;
        }

    }

A class which is labelled as abstract could not be instantiate directly. so we don't need to create constructor and overloaded constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM