How to call one constructor from another in Java? (Calling a constructor inside a constructor)
Hello colleagues! I just started learning Java and ran into a problem. I have a `User` class where I want to create several constructors with different sets of parameters. For example, one constructor takes a name and age, and the second takes a name, age, and email. I want the second constructor not to duplicate code, but simply call the first one and add the email.
Here's my code that doesn't work:
```java
public class User {
private String name;
private int age;
private String email;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User(String name, int age, String email) {
// Trying to call the first constructor, but the compiler complains
User(name, age); // Error: "Cannot find symbol"
this
```
No answers yet.
Log in to leave an answer