简体   繁体   中英

Passing parameter to anonymous class in Java

i'm trying to write anonymous inner class

interface Face{
    void seeThis(String what);
}


class Eyes {
    public void show(Face f){}
}

public class Seen {

    public void test() {
        Eyes e = new Eyes();
        e.show(new Face() {

            @Override
            public void seeThis(String what){
                System.out.print(what);
            }
        });

    public static void main(String[] args) {
        Seen s = new Seen();
        s.test();
    }
}

How to call seeThis() and how to pass parameter to it?

Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:

public class Seen {
    public Face face;

    ....

    this.face = new Face() { ... };
    e.show(this.face);

And then,

Seen s = new Seen();
s.face.seeThis();

Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:

Approach one:

final int parameter = 5;

...(new Face() {
        @Override
        public void seeThis() {
            System.out.println(parameter);
        }
    });

Approach two:

public class MyFace implements Face() {
    private final int parameter;

    public MyFace(int parameter) {
        this.parameter = parameter;
    }

    @Override
    public void seeThis() {
        System.out.println(parameter);
    }
}

Then,

...
e.show(new MyFace(10));    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM