I am beginning to learn java, and am coding a simple hockey statistics class. It looks like this:
public class Player
{
private int games;
private int goals;
private int assists;
private char position;
public Player()
{
games = 0;
goals = 0;
assists = 0;
position = 'X';
}
public Player(int initialGames, int initialGoals, int initialAssists,
char initialPosition )
{
games = initialGames;
goals = initialGoals;
assists = initialAssists;
position = initialPosition;
}
public void setPlayer(int newGames, int newGoals, int newAssists, char
newPosition)
{
games = newGames;
goals = newGoals;
assists = newAssists;
position = newPosition;
}
public Player(int initialGames)
{
games = initialGames;
goals = 0;
assists = 0;
position = 'X';
}
public void setGames(int newGames)
{
games = newGames;
}
public Player(int initialGoals)
{
games = 0;
goals = initialGoals;
assists = 0;
position = 'X';
}
}
Now, this all compiles fine until I enter the code for the last block. When I try to compile it, I get this error:
(Player.java:52 error: constructor Player(int) is already defined in class Player)
What am I doing wrong? I am following the format of my textbook quite closely to build this class, but I keep running into this error. Can anyone give me a reason why this is happening? Because I do not fully understand this compiler error.
asked Feb 6, 2018 at 4:03
DavidMDavidM
311 gold badge1 silver badge4 bronze badges
3
You have not overloaded properly.
You have 2 constructors with same signature.
public Player(int initialGoals)
{
games = 0;
goals = initialGoals;
assists = 0;
position = 'X';
}
and
public Player(int initialGames)
{
games = initialGames;
goals = 0;
assists = 0;
position = 'X';
}
So one quick solution will be merging the both constructors.
public Player(int initialGoals, int initialGames)
{
games = initialGames;
goals = initialGoals;
assists = 0;
position = 'X';
}
Have a single constructor and pass zero instead when the param is not available.
For ex
Player p = new Player(5,0); // games 0
Player p = new Player(0,5); // goals 0
answered Feb 6, 2018 at 4:09
Suresh AttaSuresh Atta
120k37 gold badges196 silver badges305 bronze badges
You duplicated the constructor, the compiler can not decide which one of those you want to call when typing new Player(8)
:
public Player(int initialGoals)
public Player(int initialGames)
Try calling new Player()
from a new set of methods
static Player NewPlayerFromGoals(int initialGoals){...}
static Player NewPlayerFromGames(int initialGames){...}
And call it with
Player p = Player.NewPlayerFromGoals(8);
answered Feb 6, 2018 at 4:08
phi1010phi1010
6786 silver badges13 bronze badges
Multiple constructors with the same parameters aren’t allowed. When creating multiple constructors have one main constructor build an object with every possible parameter. If an object is allowed to be created with less parameters then create another constructor which calls the main constructor.
public Player(int games){
this(games, 0, 0, 0);
}
public Player(int games, int goals, int assists, char position){
this.games = games;
this.goals = goals;
this.assists = assists;
this.position = position;
}
More constructors can be created to accommodate more parameters using the same format as the first constructor.
answered Feb 6, 2018 at 4:16
sellcsellc
3801 gold badge5 silver badges19 bronze badges
public Player(int initialGoals)
{
games = 0;
goals = initialGoals;
assists = 0;
position = 'X';
}
and
public Player(int initialGames)
{
games = initialGames;
goals = 0;
assists = 0;
position = 'X';
}
Have the same signature Player(int)
.
So you should change your constructors or delete one.
EDIT (I add more code for clarify)
Method 1:
enum ConstructorType {
GOAL,
GAME
}
public Player(int value, ValueType type)
{
switch(type){
case GOAL:
goals = value;
break;
case GAME:
games = value;
break;
default:
break;
}
this(games, goals, 0, 'X'); // Prefer this one instead of repeat your constructor code.
}
Method 2:
public Player(int initialGoals, int initialGames)
{
this(initialGames, initialGoals, 0, 'X');
}
answered Feb 6, 2018 at 4:08
Liem LeLiem Le
5817 silver badges17 bronze badges
2
You can’t define constructors with same parameter type. And in this case, I think you should use your first constructor + setters instead of define many constructors with just one parameter.
public class Player {
private int games;
private int goals;
private int assists;
private char position;
public Player() {
games = 0;
goals = 0;
assists = 0;
position = 'X';
}
public Player(int initialGames, int initialGoals, int initialAssists,
char initialPosition ) {
games = initialGames;
goals = initialGoals;
assists = initialAssists;
position = initialPosition;
}
// SETTER
public void setGames (int games) {
this.games = games;
}
public void setGoals (int goals) {
this.goals= goals;
}
}
And then:
Player playerA = new Player();
playerA.setGames(1);
Player playerB = new Player();
playerB.setGoals(2);
answered Feb 6, 2018 at 6:59
nemonemo
611 silver badge8 bronze badges
package com.javarush.task.task05.task0517;
/*
Конструируем котиков
*/
public class Cat {
//напишите тут ваш код
private String name, address, color;
private int age, weigt;
public Cat(String name) {
this.name = name;
this.address = null;
this.color = «grey»;
this.age = 1;
this.weigt = 1;
}
public Cat(String name, int age, int weigt) {
this.name = name;
this.address = null;
this.color = «grey»;
this.age = age;
this.weigt = weigt;
}
public Cat(String name, int age) {
this.name = name;
this.address = null;
this.color = «grey»;
this.age = age;
this.weigt = 1;
}
public Cat(String color, int weigt) {
this.name = null;
this.address = null;
this.color = color;
this.age = 1;
this.weigt = weigt;
}
public Cat(String address, String color, int weigt) {
this.name = null;
this.address = address;
this.color = color;
this.age = 1;
this.weigt = weigt;
}
public static void main(String[] args) {
}
}
I am beginning to learn java, and am coding a simple hockey statistics class. It looks like this:
public class Player
{
private int games;
private int goals;
private int assists;
private char position;
public Player()
{
games = 0;
goals = 0;
assists = 0;
position = 'X';
}
public Player(int initialGames, int initialGoals, int initialAssists,
char initialPosition )
{
games = initialGames;
goals = initialGoals;
assists = initialAssists;
position = initialPosition;
}
public void setPlayer(int newGames, int newGoals, int newAssists, char
newPosition)
{
games = newGames;
goals = newGoals;
assists = newAssists;
position = newPosition;
}
public Player(int initialGames)
{
games = initialGames;
goals = 0;
assists = 0;
position = 'X';
}
public void setGames(int newGames)
{
games = newGames;
}
public Player(int initialGoals)
{
games = 0;
goals = initialGoals;
assists = 0;
position = 'X';
}
}
Now, this all compiles fine until I enter the code for the last block. When I try to compile it, I get this error:
(Player.java:52 error: constructor Player(int) is already defined in class Player)
What am I doing wrong? I am following the format of my textbook quite closely to build this class, but I keep running into this error. Can anyone give me a reason why this is happening? Because I do not fully understand this compiler error.
asked Feb 6, 2018 at 4:03
DavidMDavidM
311 gold badge1 silver badge4 bronze badges
3
You have not overloaded properly.
You have 2 constructors with same signature.
public Player(int initialGoals)
{
games = 0;
goals = initialGoals;
assists = 0;
position = 'X';
}
and
public Player(int initialGames)
{
games = initialGames;
goals = 0;
assists = 0;
position = 'X';
}
So one quick solution will be merging the both constructors.
public Player(int initialGoals, int initialGames)
{
games = initialGames;
goals = initialGoals;
assists = 0;
position = 'X';
}
Have a single constructor and pass zero instead when the param is not available.
For ex
Player p = new Player(5,0); // games 0
Player p = new Player(0,5); // goals 0
answered Feb 6, 2018 at 4:09
Suresh AttaSuresh Atta
119k37 gold badges196 silver badges304 bronze badges
You duplicated the constructor, the compiler can not decide which one of those you want to call when typing new Player(8)
:
public Player(int initialGoals)
public Player(int initialGames)
Try calling new Player()
from a new set of methods
static Player NewPlayerFromGoals(int initialGoals){...}
static Player NewPlayerFromGames(int initialGames){...}
And call it with
Player p = Player.NewPlayerFromGoals(8);
answered Feb 6, 2018 at 4:08
phi1010phi1010
6385 silver badges13 bronze badges
Multiple constructors with the same parameters aren’t allowed. When creating multiple constructors have one main constructor build an object with every possible parameter. If an object is allowed to be created with less parameters then create another constructor which calls the main constructor.
public Player(int games){
this(games, 0, 0, 0);
}
public Player(int games, int goals, int assists, char position){
this.games = games;
this.goals = goals;
this.assists = assists;
this.position = position;
}
More constructors can be created to accommodate more parameters using the same format as the first constructor.
answered Feb 6, 2018 at 4:16
sellcsellc
3801 gold badge5 silver badges19 bronze badges
public Player(int initialGoals)
{
games = 0;
goals = initialGoals;
assists = 0;
position = 'X';
}
and
public Player(int initialGames)
{
games = initialGames;
goals = 0;
assists = 0;
position = 'X';
}
Have the same signature Player(int)
.
So you should change your constructors or delete one.
EDIT (I add more code for clarify)
Method 1:
enum ConstructorType {
GOAL,
GAME
}
public Player(int value, ValueType type)
{
switch(type){
case GOAL:
goals = value;
break;
case GAME:
games = value;
break;
default:
break;
}
this(games, goals, 0, 'X'); // Prefer this one instead of repeat your constructor code.
}
Method 2:
public Player(int initialGoals, int initialGames)
{
this(initialGames, initialGoals, 0, 'X');
}
answered Feb 6, 2018 at 4:08
Liem LeLiem Le
5717 silver badges17 bronze badges
2
You can’t define constructors with same parameter type. And in this case, I think you should use your first constructor + setters instead of define many constructors with just one parameter.
public class Player {
private int games;
private int goals;
private int assists;
private char position;
public Player() {
games = 0;
goals = 0;
assists = 0;
position = 'X';
}
public Player(int initialGames, int initialGoals, int initialAssists,
char initialPosition ) {
games = initialGames;
goals = initialGoals;
assists = initialAssists;
position = initialPosition;
}
// SETTER
public void setGames (int games) {
this.games = games;
}
public void setGoals (int goals) {
this.goals= goals;
}
}
And then:
Player playerA = new Player();
playerA.setGames(1);
Player playerB = new Player();
playerB.setGoals(2);
answered Feb 6, 2018 at 6:59
nemonemo
611 silver badge8 bronze badges
Paklosha 0 / 0 / 0 Регистрация: 09.09.2018 Сообщений: 11 |
||||
1 |
||||
08.12.2018, 13:05. Показов 19610. Ответов 3 Метки нет (Все метки)
Задумка была такой : создать базовый класс с полями,геттерами,сеттерами,потом создать класс-наследник и все протестировать.Проблема с вводом с клавиатуры в методе main (variable is already defined in the scope) Нужна помощь по решению данной проблемы.
__________________ 0 |
iSmokeJC Йуный падаван 13845 / 8089 / 2468 Регистрация: 21.10.2017 Сообщений: 19,548 |
||||
08.12.2018, 14:13 |
2 |
|||
Решение
variable is already defined in the scope Если это перевести, то все становится очевидным.
String name;
String name = in.nextLine(); Т.е. во втором случае убери объявление типа переменной, т.е.
То же самое с остальными переменными Добавлено через 3 минуты
private String Subject Переменным принято давать осмысленные имена, причем начинающиеся с маленькой буквы. С большой буквы — типы. 1 |
0 / 0 / 0 Регистрация: 09.09.2018 Сообщений: 11 |
|
08.12.2018, 16:28 [ТС] |
3 |
Спасибо большое,теперь программа работает.Но отказывается считывать переменную Subject (Программа просто пропускает ее считывание).Что это может быть? 0 |
package com.javarush.task.task05.task0510;
/*
Кошкоинициация
*/
public class Cat {
String name = null;
String address = null;
String color = "red";
int age = 9;
int weight = 6;
public void initialize(String name){
this.name = name;
this.color = "white";
this.age = 8;
this.weight = 6;
}
public void initialize(int age, int weight, String name){
this.name = name;
this.age = age;
this.weight = weight;
this.color = "black";
}
public void initialize(int age, String name){
this.weight = 20;
this.name = name;
this.age = age;
this.color = "black";
}
public void initialize(int weight, String color){
this.color = color;
this.weight = weight;
this.age = 8;
}
public void initialize(int weight, String color, String address){
this.weight = weight;
this.address = address;
this.color = color;
this.age = 7;
}
public static void main(String[] args) {
}
}
Вылазит ошибка: method initialize(int,java.lang.String) is already defined in class com.javarush.task.task05.task0510.Cat:
Cat.java, line: 34, column: 17
Компилировал ideone.com/gA6knT
Скрипт:
class HelloWorld {
public static void main(String[] args) {
// int x = 10;
for (int x = 1; x<11; x=x+1){
if(x==1){
String name = "бутылка";
}
if(x==2 | x==3 | x==4){
String name = "бутылки";
}
if(x > 4 & x < 21){
String name = "бутылок";
}
System.out.println("У нас есть " + x + name);
}
}
}
Он говорит что отсутствует переменная name я так понял (cannot find symbol symbol: variable name), так вроде для всех вариантов присутствующих в цикле она определена…
Второй вопрос: в 3 строке закомментировано int x = 10; если раскомментировать то он ругается на for (int x = 1 и говорит что переменная уже определена выше. Так JAVA не поддерживает переопредление как в php или это как-то по-другому делается?
-
Вопрос заданболее трёх лет назад
-
2949 просмотров
1. Проблема в области видимости переменной name. Вынесите String name = null; перед циклом, а в цикле уже определяйте ее (name = ….)
2. используйте for(x =1; x<11; x++)
Нужно вне If инициализировать переменную.
И объявление должно быть одно в рамках одного метода.
Что-то типа такого должно быть
class HelloWorld {
public static void main(String[] args) {
// int x = 10;
String name = "";
for (int x = 1; x<11; x=x+1){
if(x==1){
name = "бутылка";
Пригласить эксперта
Вот за это по рукам надо бить.if(x > 4 & x < 21){
И да, прочитайте про области видимости переменных.
-
Показать ещё
Загружается…
28 янв. 2023, в 22:48
500 руб./за проект
28 янв. 2023, в 20:58
30000 руб./за проект
28 янв. 2023, в 20:46
50000 руб./за проект
Минуточку внимания
Ошибка
java: constructor Restaurant() is already defined in class
com.example.order_system.domain.Restaurant
Появляются, когда я добавляю этот класс и запускаю программу
@Entity
@NoArgsConstructor
@RequiredArgsConstructor
@Getter
@Setter
@ToString
public class Restaurant {
@Id
@GeneratedValue
private long id;
@NotEmpty(message = "The restaurant must have a name")
private String name;
@NotEmpty(message = "Please add a description for this restaurant")
private String description;
@NotEmpty(message = "The restaurant must have a location")
private String location;
@OneToMany(mappedBy = "restaurant", fetch = FetchType.EAGER)
private List<ContactDetails> contactDetails = new ArrayList<>();
}
2 ответа
Лучший ответ
Как упоминалось в документации, @RequiredArgsConstructor создается с использованием полей final
:
@RequiredArgsConstructor создает конструктор с 1 параметром для каждого поля, требующего специальной обработки. Все неинициализированные final поля получают параметр, а также любые поля, помеченные как @NonNull, которые не инициализированы там, где они объявлены. Для полей, отмеченных @NonNull, также создается явная проверка на null. Конструктор выдаст исключение NullPointerException, если какой-либо из параметров, предназначенных для полей, отмеченных @NonNull, содержит значение null. Порядок параметров соответствует порядку, в котором поля появляются в вашем классе.
Поэтому либо удалите аннотацию @RequiredArgsConstructor, либо отметьте некоторые поля ключевым словом final
(или аннотацией @NonNull).
2
rkosegi
21 Фев 2021 в 11:25
Попробуйте изменить @RequiredArgsConstructor на @AllArgsConstructor, и все прошло хорошо. Дополнительные сведения см. В документации
1
Dmitrii Bykov
21 Фев 2021 в 11:29
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Hello all.
I’m building a Java webapp and I’m also creating a Session API is handle all my session stuff.
I have one problem..
I’ve got these 2 methods defined and compiled:
When I try and add this..
I get the following compilation error:
It’s lets me define get() with two different data types but when I add a third different data type (ArrayList()) it says get() is already defined. Any ideas? Help much appreciated!
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
ArrayList has a built in method named get() and I suspect there is a naming collision.
I suspect that if you were to rename this to something like getSessionID() then things would work fine.
Or possibly your package name is missing or not defined correctly?
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
Michael Portman
Ranch Hand
Posts: 129
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Pete Letkeman wrote:ArrayList has a built in method named get() and I suspect there is a naming collision.
I suspect that if you were to rename this to something like getSessionID() then things would work fine.
Or possibly your package name is missing or not defined correctly?
My package name is:
I have a setter method for it as well (which compiles, as I’ve got 3 setter methods with the same name (set()) just different data types:
What has this got to do with the session id? Dont mean to be rude lol
Pete Letkeman
Bartender
Posts: 1868
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Right now, I’m just grasping as straws, hoping to help you out as I’m somewhat new to Java myself.
I suspect, but I could be 100% wrong, that for whatever reason the Java is being tripped up and it thinks that you are trying to override a built in method of ArrayList.
I understand that you wish to use a method name get. However does this work when you change the name of the method?
Michael Portman wrote:What has this got to do with the session id? Dont mean to be rude lol
Nope, you are 100% fine. I just threw out session id as example.
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
Michael Portman
Ranch Hand
Posts: 129
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Pete Letkeman wrote:Right now, I’m just grasping as straws, hoping to help you out as I’m somewhat new to Java myself.
I suspect, but I could be 100% wrong, that for whatever reason the Java is being tripped up and it thinks that you are trying to override a built in method of ArrayList.
I understand that you wish to use a method name get. However does this work when you change the name of the method?
Michael Portman wrote:What has this got to do with the session id? Dont mean to be rude lol
Nope, you are 100% fine. I just threw out session id as example.
Dont forget HashHap has got a get() method too and that works..
Pete Letkeman
Bartender
Posts: 1868
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Michael Portman wrote:Dont forget HashHap has got a get() method too and that works..
Yes, I do understand this and I’m not disagreeing with you in any way.
In the even that you change the name of the method from get to something else does your code compile?
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
Michael Portman
Ranch Hand
Posts: 129
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Pete Letkeman wrote:
Michael Portman wrote:Dont forget HashHap has got a get() method too and that works..
Yes, I do understand this and I’m not disagreeing with you in any way.
In the even that you change the name of the method from get to something else does your code compile?
It will work if I do that but I shouldn’t have to if you know what I mean?
Pete Letkeman
Bartender
Posts: 1868
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Oh, I think I see what may be the issue:
You have these methods in the same class:
public Map<String, String> get()
public ArrayList<String> get()
You cannot do that. This is illegal, because the names are the same.
When you are overriding methods you need to keep the same parameter/argument list and return a covarient type.
When you are overloading you need change the parameter/argument list.
So you are trying to override the get method, which you have already defined.
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
Pete Letkeman
Bartender
Posts: 1868
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
If we take out the extra objects then we can bring this back to the following:
Either on either line 2 you would need to change the name or on line 3 you would need to change the name.
Line 4 works fine, this is a valid overload as the parameter/arg list has changed.
Edit: Invalid comments in code fixed
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
Michael Portman
Ranch Hand
Posts: 129
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Pete Letkeman wrote:Oh, I think I see what may be the issue:
You have these methods in the same class:
public Map<String, String> get()
public ArrayList<String> get()
You cannot do that. This is illegal, because the names are the same.
When you are overriding methods you need to keep the same parameter/argument list and return a covarient type.
When you are overloading you need change the parameter/argument list.
So you are trying to override the get method, which you have already defined.
So to summarize I can only have:
and not:
Is there anyway around this as I want them to have the same method name, it just looks cleaner..
Pete Letkeman
Bartender
Posts: 1868
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Michael Portman wrote:Is there anyway around this as I want them to have the same method name, it just looks cleaner.
From what I know, no there is no way to do exactly what you want.
There may be some way that you could do this with inner classes or inner interfaces, of which I do not know too much about.
However now that you know the exact cause of the problem it may be worth it to start a new thread so that some other people can chime in with advice/help.
There are some people on this site who are really well versed in Java.
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
The method signature is based on the method’s name and the parameter types only — the method’s return type is not part of the signature.
In your class
public Map<String, String> get()
public ArrayList<String> get()
have the same signature, which is why you are getting a error message stating that
method get() is already defined in class Session
.
You could fix the problem by giving one of the methods a different name (maybe something like
getList()
for the method which returns an
List
).
Michael Portman
Ranch Hand
Posts: 129
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Pete Letkeman wrote:
Michael Portman wrote:Is there anyway around this as I want them to have the same method name, it just looks cleaner.
From what I know, no there is no way to do exactly what you want.
There may be some way that you could do this with inner classes or inner interfaces, of which I do not know too much about.
However now that you know the exact cause of the problem it may be worth it to start a new thread so that some other people can chime in with advice/help.
There are some people on this site who are really well versed in Java.
Im mainly a PHP developer by trade. I’ve known and practiced PHP since PHP4 and I have many projects. I want to learn Java to the same level of knowledge of my PHP experience. The main reason for this is because where I live (the UK) there is a shortage of Java Web Developers and Java Web Developers get paid more than PHP Developers. Dunno about you tho..
Michael Portman
Ranch Hand
Posts: 129
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Ron McLeod wrote:The method signature is based on the method’s name and the parameter types only — the method’s return type is not part of the signature.
In your class
public Map<String, String> get()
public ArrayList<String> get()
have the same signature, which is why you are getting a error message stating that
method get() is already defined in class Session
.
You could fix the problem by giving one of the methods a different name (maybe something like
getList()
for the method which returns an
List
).
Ill have to do that then. As I’m forced to . Oracle should allow us to this.
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
When renaming, maybe try and make the method names more specific as well so that they describe what you are returning. You may find later, that you may want to get other information as well. For example, if the
get
methods are returning attributes, you could name the methods something like:
String getAttributeValue(String name)
List<String> getAttributeNames()
Map<String, String> getAttributeMap()
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Michael Portman wrote:Oracle should allow us to this.
I don’t think it should.
Consider this example. It is the same case you tried (two methods with the same name and parameters but with different return type).
You want this to be possible:Let’s create an implementation:And now it’s time to use it.In your opinion, what should this program print?
Marshal
Posts: 77152
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Michael Portman wrote:. . . Oracle should allow us to this.
Apart from the fact that Paweł has already shown why this should not be permitted, don’t blame Oracle. That definition of method signatures goes back long before Oracle were involved with Java®, probably back to the days of JDK1.0.
The Java® Language Specification calls two methods with the same signature override‑equivalent (two hits in the index: 1 2) and there are restrictions on two override‑equivalent methods being permitted to compile.
Michael Portman
Ranch Hand
Posts: 129
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
OK it doesn’t matter, we don’t need to make an issue of it. I can simply rename the method. Job done. Issue closed.
@dreis2211
Anyhow, I wonder why this isn’t reflected in the release changelog that this breaks with
@NoArgsConstructor
already being defined. (If it is intended after all).
I’d bet, this is a bug. The only sensible behavior is the explicit annotation taking precedence, i.e., @Value
implying a weak @NoArgsConstructor(access=PRIVATE)
which gets discarded in case an explicit @NoArgsConstructor
is present.
And because the new feature adds a private no-args constructor I wonder how we can change the visibility modifier of the constructor?
IMHO, these two rules make sense:
- explicit wins over implicit
- higher visibility wins (as each annotation adds a feature, combining them means getting the higher visibility as with a
public
thing you can do everything what you can do with aprivate
one)
In this case both rules agree that there should be a public
constructor.
As mentioned in documentation @RequiredArgsConstructor is built using final
fields:
@RequiredArgsConstructor generates a constructor with 1 parameter for
each field that requires special handling. All non-initialized final
fields get a parameter, as well as any fields that are marked as
@NonNull that arent initialized where they are declared. For those
fields marked with @NonNull, an explicit null check is also generated.
The constructor will throw a NullPointerException if any of the
parameters intended for the fields marked with @NonNull contain null.
The order of the parameters match the order in which the fields appear
in your class.
So either remove @RequiredArgsConstructor annotation or mark some of fields with final
keyword (or @NonNull annotation).
Try to change @RequiredArgsConstructor to @AllArgsConstructor and thats been fine.
See more in documentation
java error : constructor is already defined in class – using lombok