Search code examples
javaabstract-class

How do I collect all the οbjects created from abstract class in a arraylist


How do I collect all the οbjects created from abstract class in a arraylist?

Here is what i've tried so far :

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, );
    }
}

Solution

  • 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
        
        }
     }