1
public class Category 
{ 
  private static Integer id; 
  private static String name; 
  public Category(Integer id, String name) 
  {
     this.id = id; 
     this.name = name; 
  } 
  public Integer getId() 
  { 
    return this.id; 
  } 
  public String getName() 
  { 
    return this.name; 
  }
}


    Category[] test = new Category[2];
    test[0] = new Category(1,"Link");
    test[1] = new Category(1,"Sanfe");
    System.out.println(test[0].getName());
    System.out.println(test[1].getName());

Вывод: Sanfe Sanfe Что не так делаю, тоже самое если сделать ArrayList

7
  • public String getName() { return this.name; } этот метод внутри класса Category 25 мая 2017 в 16:35
  • Кажется ты забыл добавить что должно выводить. ну и сам класс Category 25 мая 2017 в 16:38
  • код конструктора Category?
    – user176262
    25 мая 2017 в 16:38
  • public class Category { private static Integer id; private static String name; public Category(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return this.id; } public String getName() { return this.name; } } 25 мая 2017 в 16:39
  • уберите static. Заодно, выясните, что это такое.
    – user176262
    25 мая 2017 в 16:41

1 ответ 1

3

Поля класса, помеченные static, существуют в одном экземпляре для всех объектов данного типа. Исправьте на:

private Integer id; 
private String name; 

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.