[英]How do I declare an object as field in Java?
I keep getting the Java error The constructor LocalDate (int, int, int) is not visible
.我不断收到 Java 错误
The constructor LocalDate (int, int, int) is not visible
。 I am trying to create a private field and initialize it.我正在尝试创建一个私有字段并对其进行初始化。
How do I do this properly:我该如何正确执行此操作:
import java.time.LocalDate;
public class Registration {
private registrationDate = new LocalDate.of (0,0,0);
}
...
Probably the biggest issue is that you shouldn't be using the new
keyword because you aren't invoking LocalDate
's constructor.可能最大的问题是您不应该使用
new
关键字,因为您没有调用LocalDate
的构造函数。 LocalDate.of()
is just a method that you would call like any other. LocalDate.of()
只是一种您可以像其他方法一样调用的方法。
You also should declare what type registrationDate
is.您还应该声明
registrationDate
是什么类型。 So try:所以尝试:
private LocalDate registrationDate = LocalDate.of(0,0,0);
Try this.尝试这个。
private LocalDate registrationDate = LocalDate.of(0,0,0);
Two errors were there, first is that you have not declared the type of variable registrationDate
and the second is that new
is not required here as you are using a static method of LocalDate
class.有两个错误,第一个是您没有声明变量
registrationDate
的类型,第二个是这里不需要new
因为您使用的是LocalDate
类的静态方法。
LocalDate.of
is what you call in Java a static method. LocalDate.of
是您在 Java 中所说的静态方法。 Static methods do not require you to create a new version of the class.静态方法不需要您创建类的新版本。 Instead, everything they need to operate is passed into the method via it's parameters.
相反,他们需要操作的一切都通过它的参数传递到方法中。 To fix this, remove the
new
keyword.要解决此问题,请删除
new
关键字。
You are also not setting the type of the registrationDate object.您也没有设置 registrationDate 对象的类型。 Unlike other languages like Kotlin that can infer type, in Java you need to state exactly what the type is.
与 Kotlin 等其他可以推断类型的语言不同,在 Java 中,您需要准确说明类型是什么。 To do this, you'll need to put a LocalDate in between
private
and registrationDate
.为此,您需要在
private
和registrationDate
之间放置一个 LocalDate 。
Putting that all together, it should look like this:把所有这些放在一起,它应该是这样的:
private LocalDate registrationDate = LocalDate.of(0,0,0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.