Baked Inhalf
Baked Inhalf

Reputation: 3735

Java OOP instantiate self or add subclass?

So the main animal class will generate som cows, but the instantiation is made in the cow class. My question is: Is this code pattern really "ok"? Or should the cow class be renamed to "CowHandler" and instead have a subclass named cow?

CowHandler would then have a field List<Cow> cows; and Cow class only String name;

It just feels strange for the cow class to instantiate itself, for example the field with list of cows is never used from within the cow class. Here is the code as of now:

Animal class

import java.util.List;

public class Animal
{
    public static void main(String[] args)
    {
        Animal animal = new Animal();
        animal.init();
    }


    private void init()
    {
        Cow cow = new Cow();

        int count = cow.getCows().size();
        System.out.println("Cows in list before: " + count);

        List<Cow> manyCows = cow.makeSomeCows();

        for (Cow c : manyCows)
        {
            System.out.println(c.getName());
            System.out.println("Children?: " + c.getCows().size());
            System.out.println("");
        }

        count = cow.getCows().size();
        System.out.println("Cows in list after: " + count); 
    }
}

Cow class

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

public class Cow
{
    private String name;
    private List<Cow> cows;

    public Cow()
    {   
        cows = new ArrayList<Cow>();
    }


    public List<Cow> makeSomeCows()
    {
        for (int i=0; i<10; i++)
        {
            Cow cow = new Cow();
            cow.name = "Tiny cow " + ((char)(i + 65));
            cows.add(cow);
        }
        return cows;
    }


    public String getName()
    {
        return this.name;
    }


    public List<Cow> getCows()
    {
        return this.cows;
    }

}

Output:

Cows in list before: 0
Tiny cow A
Children?: 0

Tiny cow B
Children?: 0

Tiny cow C
Children?: 0

Tiny cow D
Children?: 0

Tiny cow E
Children?: 0

Tiny cow F
Children?: 0

Tiny cow G
Children?: 0

Tiny cow H
Children?: 0

Tiny cow I
Children?: 0

Tiny cow J
Children?: 0

Cows in list after: 10

Upvotes: 1

Views: 63

Answers (1)

Eran
Eran

Reputation: 393856

Having a private List<Cow> cows; instance variable in the Cow class only makes sense if each Cow instance has a list of Cows somehow related to it (for example, the children of that Cow).

If the purpose is to have a container of all the Cows you created, an instance variable in the Cow class is wrong, since each Cow object would have its own List<Cow>.

You could use a private static List<Cow> cows; static variable in the Cow class to hold all the Cow instances, with corresponding static methods to access it, but it makes more sense to put the list on a separate container of Cows, such as CowHandler. Note, however, that it doesn't make sense for Cow to be a sub-class of CowHandler. A Cow is not a Cowhandler.

Upvotes: 1

Related Questions