简体   繁体   中英

Method with an Interface as a parameter

class Do{
    void doit(){
        ClassA a = new ClassA();
        a.doSomething(>>>CODE HERE<<<);
    }
}
interface InterfaceA{
    void doSomethingElse();
}
class ClassA{
    void doSomething(InterfaceA f){
    }
}

Question: Complete the above code so that doit method prints "Hello world!" by adding the code only between parentheses as denoted and not changing anything else.

Could somebody please help me to solve this? I still have no clue. I left it blank in the quiz yesterday :((. Thanks for your help

class Do{
    void doit(){
        ClassA a = new ClassA();
        a.doSomething(new InterfaceA () {
             { System.out.println("Hello world"); }
             @Override public void doSomethingElse() { }
             });
    }
}

The key is to define an anonymous class with an initializer, and then use "new" to create a new object of that class. Creating the object executes the initializer. PS This has been tested.

This doesn't seem like a good quiz question; doing something like this is pretty obscure and probably not the normal sort of thing one would actually code. It looks more like a puzzle than an actual test question. Unless there's a better answer I haven't spotted...

OK, if the quiz question looked like this:

class Do{
    void doit(){
        ClassA a = new ClassA();
        a.doSomething(>>>CODE HERE<<<);
    }
}
interface InterfaceA{
    void doSomethingElse();
}
class ClassA{
    void doSomething(InterfaceA f){
        // NOTE THIS CHANGE!
        f.doSomethingElse();
    }
}

Then you can change this:

a.doSomething(>>>CODE HERE<<<);

To this:

a.doSomething(new InterfaceA() {
    @Override public void doSomethingElse() {
        System.out.println("Hello world!");
    }
});

Otherwise the answer is something bizarre like the other answers are saying.

I don't know if this is the intended answer to the quiz, but this should work:

class Do{
    void doit(){
        ClassA a = new ClassA();
        a.doSomething(null); System.out.println("Hello world!");
               //    ^ starting paren           closing paren ^
    }
}
interface InterfaceA{
    void doSomethingElse();
}
class ClassA{
    void doSomething(InterfaceA f){
    }
}

Basically by just putting the two lines on the same line, you don't have to provide an implementation for the interface. The only added code then is null); System.out.println("Hello world!" null); System.out.println("Hello world!"

Inspired by: http://xkcd.com/327/

This is probably more of a riddle-like answer to what's intended to be a technical quiz...unless your teacher was trying to have some fun with you.

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