0

Just looking for a clear definition of the following:

When you include ArrayList<Product> in the class declaration, and product being another class that holds some instance variables. When using the code shown below, Is the ArrayList initialized on creation of the object?

For example :

public class Basket extends ArrayList<Product> implements Serializable
{
  private int    theOrderNum = 0;          // Order number

  public Basket()
  {
   theOrderNum  = 0;
  }

}

If I create an instance of the new class :

Basket test = new Basket(); 

Would that create an array list on the object being created? In order to access the ArrayList inside the object, could I use this.add(foo); ?

Eran
  • 387,369
  • 54
  • 702
  • 768
user3023003
  • 53
  • 1
  • 7

4 Answers4

2

A class that extends ArrayList, has all the methods of ArrayList. Instantiating this class would create an ArrayList, since Basket is an ArrayList. You can call all the public methods of ArrayList on your test instance.

test.add(foo) (and this.add(foo) from within non-static methods of the Basket class) would work.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Call the constructor of your extended class as :

public Basket()
{
   super();
   theOrderNum  = 0;
}

However you should prefer composition over inheritance on many cases such as yours :

Prefer composition over inheritance?

Community
  • 1
  • 1
Pumpkin
  • 1,993
  • 3
  • 26
  • 32
  • I was unsure initially if he would need to call the super constructor, so I wrote a quick test and it works without calling `super()` (although adding `super()` doesn't seem to break anything) – Neilos Oct 23 '14 at 14:39
  • @Neilos Yes you don't need to call `super();` explicitly, the compiler will automatically add it for you. As the ArrayList class has a no arg constructor, you don't get any errors. – user2336315 Oct 23 '14 at 14:47
0

Inside Basket, the ArrayList, which is the Basket, can be use through this

Example, in aMethod

public class Basket extends ArrayList<Product> implements Serializable
{

    // [...]

    public void aMethod()
    {
        add(new Product());
        System.out.prinln(size());
    }
}

With a test instance, same way :

Basket test = new Basket(); 
test.add(new Product());
Iterator i = test.iterator();
test.aMethod();
ToYonos
  • 16,469
  • 2
  • 54
  • 70
0

When you inherit a class A from a class B, all the public and protected members and methods will be usable/callable unless you override them. As a result, if you inherit your class from ArrayList, you can call its public methods. The constructor of the base class might be doing some initializations, therefore it is not a bad idea to call super in the constructors of your subclass.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175