【问题标题】:How to assign the inherited variables to the arrayList object of a subclass如何将继承的变量分配给子类的arrayList对象
【发布时间】:2021-01-08 21:05:53
【问题描述】:

我有一个abstract class Element:

public abstract class Element{
    String nom;
    int prix;

    // constructor
    public Element(String n, int p) {
        this.nom = n;
        this.prix = p;
    }

    //getters
    public String getNom() {
        return nom;
    }

    public int getPrix() {
        return prix;
    }
}

我有一个subclass Bag,它从class Element 扩展而来,其特征在于它的重量(poids)和颜色(couleur)。但是Bag 也包含一个对象列表(对于对象类)。

所以我想做的是在我的subclass Bag 中创建一个arrayList<superclass>,以便能够编写代码来表示这些对象:一个苹果(一个苹果的价格:7 红宝石)、一个香蕉( price = 5 rubies)和一条 Fish(price = 20 rubies),也可以在袋子中添加或移除物品。

我的问题是: 如何将继承的变量分配给我的“Bag”子类的对象arraylist objectsInBag

我正在使用 question 中的代码,如果我尝试的方法很好,应该如何创建子类的构造函数,包括 arrayList objectsInBag

我到目前为止的代码:

import java.util.ArrayList;

public class Bag extends Element{

// atributtes propres a Bag
private String couleur;
private Integer poids;

ArrayList<Object[]> objectsInBag = new ArrayList<>();


// constructor

public Bag(String n, Integer p, String couleur, Integer poids ) {
    
    super(n, p);
    this.couleur = couleur;
    this.poids = poids;
}

// adding object into the bag
public void addObjects(String n, Integer p){
    objectsInBag.add(new Object[]{getNom(), getPrix()});
}

// getters and setters

public String getCouleur(){
    return this.couleur;
}

public void setCouleur(String couleur){
    this.couleur = couleur;
}

public Integer getPoids(){
    return this.poids;
}

public void setPoids(Integer poids){
    this.poids = poids;
}

【问题讨论】:

  • 为什么要把 Object[] 放在 ArrayList 中?
  • 另外,为什么超类必须是抽象的?它没有任何抽象方法。
  • 我不能修改抽象类(这是练习的规则)...我正在使用 Object[] 因为它允许为 arrayList 设置多个参数,因为我旨在获取类型为 [ {banana: 5} , {apple: 7} , {fish: 20}] 的 arrayList,然后能够在 arrayList 中添加或删除元素

标签: java inheritance arraylist


【解决方案1】:

据我了解,您正在尝试做两件事:

  1. 超类 Objet(误导很多,最好重命名为 Thing 或与标准 java Object 不同的抽象名称)及其继承者:Apple、Banana、Fish
  2. Bag 是一个容器,可以存放一些东西。

为此,您必须有一个层次结构:

abstract class Thing{
  private final String nom;
  private final int prix;
  //+ constructor, getters
}

class Apple extends Thing {
 //+constructor that just calls `super(nom, prix)`
}

class Banana extends Thing {
 //+constructor that just calls `super(nom, prix)`
}

class Fishextends Thing {
 //+constructor that just calls `super(nom, prix)`
}

容器Bag 将被生成为Thing 类型,就像这样:

class Bag<T> {
  // atributtes propres a Bag
  private final String couleur;
  private final Integer poids;
  //+ constructor, getters
  private final List<T> list = new ArrayList<>();

  addItem(T item){
    list.add(item);
  }

  removeItem(T item){
    list.remove(item);
  }
}

你可以这样使用它:

Bag<Thing> bag = new Bag<>("couleur", 5);
bag.addItem(new Apple("rubies", 7));
bag.addItem(new Banana ("rubies", 5));
bag.addItem(new Fish("rubies", 20));

【讨论】:

  • 谢谢,但是有必要为每件事都创建一个类吗?如果那时我必须创建一个椰子并删除一个香蕉?应该有必要为椰子创建另一个类吗?
  • 没有必要。您可以将Thing 不抽象并添加name 字段,以便您调用new Thing("Apple", "rubies", 7)
  • 正在处理您的代码,因为它似乎很合适,无论如何,当我将项目“添加”到包时,我会收到此错误:Bag 是原始类型。对泛型类型 Bag 的引用应该被参数化
  • 是的,我似乎有一个错字:应该是Bag&lt;Thing&gt; bag = new Bag&lt;&gt;("couleur", 5);。对不起:)
  • 现在很好!但是如果我想迭代包,例如知道长度或打印包内的物品,那么正确的方法是什么?我正在使用System.out.println("Size of ArrayList = " + bag.size()); 或者:for (String item : bag){ System.out.println("Thing: " + item); },但我得到:只能遍历数组或 java.lang.Iterable 的实例
【解决方案2】:

您似乎需要修改类Bag 以拥有BagItem 实例列表而不是List&lt;Object[]&gt;BagItem 应该是 AppleBananaFish 等的超类,并且可能有一个字段将包项与特定包关联。

public class Bag extends Objet {

    // atributtes propres a Bag
    private String couleur;
    private Integer poids;

    List<BagItem> objectsInBag = new ArrayList<>();

    public Bag(String n, Integer p, String couleur, Integer poids ) {
        super(n, p);
        this.couleur = couleur;
        this.poids = poids;
    }

    // adding object into the bag
    public boolean addItem(BagItem item) {
        item.setBag(this);
        return objectsInBag.add(item);
    }

    // remove object from bag
    public boolean removeItem(BagItem item) {
        Objects.requireNonNull(item);
        boolean res = objectsInBag.remove(item);
        if (res) {
            item.setBag(null); // clear reference to bag if removal succeeded
        }
        return res;
    }
}
public class BagItem extends Objet {
    private Bag bag;

    public BagItem(String n, Integer p) {
        this(n, p, null); // unknown bag
    }

    public BagItem(String n, Integer p, Bag bag) {
        super(n, p);
        if (null != this.bag) {
            this.bag.addItem(this);
        }
    }

    public void setBag(Bag bag) {
        this.bag = bag;
    }
}

扩展BagItem 的示例类——可能只需要重新定义构造函数:

public class Apple extends BagItem {
    public Apple(String n, Integer p) {
        this(n, p, null);
    }

    public Apple(String n, Integer p, Bag bag) {
        super(n, p, bag);
    }
}

用法:

  • 创建Bag 实例
  • 创建具体的BagItem 实例(可选择使用Bag 实例)
Bag redBag = new Bag("myBag", 5, "Red", 10);
// added immediately
Apple apple1 = new Apple("Golden", 7, redBag);

// added via .addItem
Apple apple2 = new Apple("Jonagold", 8);
redBag.addItem(apple2);

System.out.println("remove golden apple: " + redBag.removeItem(apple1));

【讨论】:

  • @MiguelGIS,用一个使用示例更新了答案
【解决方案3】:

如果我理解正确,您只想在子类的构造函数中包含数组的初始化。您可以像这样更改代码:

public class Bag extends Element{

    // atributtes propres a Bag
    private String couleur;
    private Integer poids;

    // constructor
    public Bag(String n, Integer p, String couleur, Integer poids ) {
        super(n, p);
        this.couleur = couleur;
        this.poids = poids;
        ArrayList<Object[]> objectsInBag = new ArrayList<>();
    }

    // adding object into the bag
    public void addObjects(String n, Integer p){
        objectsInBag.add(new Object[]{n, p});
    }

    // getters and setters
    public String getCouleur(){
        return this.couleur;
    }

    public void setCouleur(String couleur){
       this.couleur = couleur;
    }

    public Integer getPoids(){
        return this.poids;
    }

    public void setPoids(Integer poids){
       this.poids = poids;
    }
}

【讨论】:

    【解决方案4】:

    我使用@MikhailKopylov 的答案并应用多态性原理解决了它:

    所以,abstract class Element

    public abstract class Element{
        String nom;
        int prix;
    
        // constructor
        public Objet(String n, int p) {
            this.nom = n;
            this.prix = p;
        }
    
        //getters
        public String getNom() {
            return nom;
        }
    
        public int getPrix() {
            return prix;
        }
    
    }
    
    // the name and price of each object are already determined in the Apple, Banana and Fish classes
    
    class Apple extends Element {
    //+constructor that just calls `super(nom, prix)`
    public Apple(String n, int p) {
        super("Pomme", 7);
    }
    
    }
    
    class Banana extends Element {
    //+constructor that just calls `super(nom, prix)`
    public Banana(String n, int p) {
        super("Banane", 5);
    }
    }
    
    class Fish extends Element {
    //+constructor that just calls `super(nom, prix)`
    public Fish(String n, int p) {
        super("Poisson", 20);
    }
    }
    

    还有subclass Bag

    public class Bag{
    
    // atributtes propres a Bag
    private String couleur;
    private Integer poids;
    
    // constructor
    public Bag(String couleur, Integer poids ) {
        this.couleur = couleur;
        this.poids = poids;
    }
    
    // getters and setters
    public String getCouleur(){
        return this.couleur;
    }
    
    public void setCouleur(String couleur){
       this.couleur = couleur;
    }
    
    public Integer getPoids(){
        return this.poids;
    }
    
    public void setPoids(Integer poids){
       this.poids = poids;
    }
    
    // Polymorphism
    
    //creation of the list of object types, which allows to go on the concept of polymorphism to access the attributes of the Object class, and to assign them to an arrayList of the Bag class
    
    List<Element> objetos = new ArrayList<Element>();
    
    public void addItem(Element item){
        objetos.add(item);
      }
    
    public void removeItem(Element item){
        objetos.remove(item);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2015-05-29
      • 1970-01-01
      相关资源
      最近更新 更多