Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
Ramkay Avatar asked Aug 15 '26 13:08

Ramkay


1 Answers

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

like image 162
Smutje Avatar answered Aug 17 '26 04:08

Smutje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!