Ramkay
Ramkay

Reputation: 31

Java Abstract Class Method

I came across this code in an exercise for declaring an abstract class:

import java.util.ArrayList;

public abstract class Box {

    public abstract void add(Item item);

    public void add(ArrayList<Item> items) {
        for (Item item : items) {
            Box.this.add(item);
        }
    }

    public abstract boolean isInBox(Item item);
}

I am not able to understand what the add(ArrayList<Item> item) method does. I get it that it loops through an ArrayList called items but what does Box.this.add(item) do? Can someone clarify this?

Upvotes: 3

Views: 198

Answers (2)

Baltasarq
Baltasarq

Reputation: 12202

That class is declaring an interface with some code already in. Specifically, it is declaring a Box without a detailed implementation, in which you can later create the Box with the underlying code that suits your needs.

For example, you can declare the BoxOnSet class, that implements that declaration with a HashSet<>:

public abstract class BoxOnSet extends Box {
    public BoxOnSet()
    {
        this.items = new HashSet<>();
    }

    public void add(Item item)
    {
        this.items.add( item );
    }


    public boolean isInBox(Item item)
    {
        return this.items.contains( item );
    }

    private HashSet<Item> items;
}

As for your specific question, the add(ArrayList<>) method is equivalent to the collections addAll() method. It just uses the abstract add(Item) in order to insert items in the Box. You can specify add( item ), this.add( item ) or even Box.this.add( item ), and in this example all point to the same method, they are just ways to specify further.

Upvotes: 0

Smutje
Smutje

Reputation: 18123

On top of what @ernest_k wrote in a comment there is an actual use-case where you actually need to qualify a method call with the class name like this: If you create an anonymous inner class in a method that accesses fields of its outer class, like the following arbitrary (and quite useless in reality) example:

import java.util.ArrayList;

public abstract class Box {

    public abstract void add(String item);

    public void add(ArrayList<String> items) {
        for (String item : items) {
            Runnable r = new Runnable() {

                @Override
                public void run() {
                    add(item); // works, implicitly accesses Box.this.add
                    this.add(item); // does not work as "add" is not a method of the anonymous runnable
                    Box.this.add(item); // works
                }
            };
            r.run();
        }
    }

    public abstract boolean isInBox(String item);
}

Upvotes: 4

Related Questions