如何在arraylist中收集从抽象类创建的所有对象

问题描述

如何将抽象类创建的所有对象收集到数组列表中?

这是我迄今为止尝试过的:

package exercice3;

import java.util.ArrayList;
import java.util.List;

public abstract class Personne {
    
    protected String nom ;
    protected String prenom ; 
    protected String adresse ;
    protected static int nbPersonnes = 0 ; 
    List<Personne> ListePersonnes = new ArrayList <>();
    
    public Personne(String nom,String prenom,String adresse) {
        
        this.nom= nom ; 
        this.prenom = prenom ; 
        this.adresse = adresse ; 
        nbPersonnes++;
        ListePersonnes.add(nbPersonnes,);
    }
}

解决方法

public abstract class Personne {
           
    protected String nom ;
    protected String prenom ; 
    protected String adresse ;
    protected static int nbPersonnes = 0 ; 
    static List<Personne> ListePersonnes = new ArrayList<>();
    
    
    
    public Personne(String nom,String prenom,String adresse) {
        
        this.nom= nom ; 
        this.prenom = prenom ; 
        this.adresse = adresse ; 
        nbPersonnes++;
        ListePersonnes.add(this);  // <== use 'this' keyword
    
    }
 }