[英]How do I create a public default constructor and an overloaded constructor?
I am extremely new to Java and coding in general. 我对Java和一般编码非常陌生。 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.
我正在一个项目中创建了两个接口,现在正在创建一个名为VehicleChassis的具体类来实现我的Chassis接口。 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.
现在,我需要使用以下值创建一个默认的构造函数和重载的构造函数-一个带有到底盘参数的String值。 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. 您将无法实例化此
VehicleChassis
因为您已将其声明为抽象。 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
. 如果您不打算在
Chassis
实现所有方法,请将VehicleChassis
保持为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.
因此我们不需要创建构造函数和重载的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.