简体   繁体   中英

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 . 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. LocalDate.of() is just a method that you would call like any other.

You also should declare what type registrationDate is. 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.

LocalDate.of is what you call in Java a static method. 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.

You are also not setting the type of the registrationDate object. Unlike other languages like Kotlin that can infer type, in Java you need to state exactly what the type is. To do this, you'll need to put a LocalDate in between private and registrationDate .

Putting that all together, it should look like this:

private LocalDate registrationDate = LocalDate.of(0,0,0);

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