2

I came across a piece of code that I don't entirely understand.

There is an interface that is created within a class like this:

public class SomeClass {

    public interface SomeInterface{
        public String getInfo(String str1, String str2);
    }

    public static final SomeInterface SomeOtherName = new SomeInterface() {

            @Override
            public String getInfo(String str1, String str2){
                //return something;
            }
        }
    }

and then in another class they call the method getInfo using SomeOtherName. I don't understand what is going on here. To be honest I have not created an interface while in a class and then create an object of that interface type and then override methods in it. Can someone please explain me what is going on in this piece of code as I need to test it.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
user3044240
  • 621
  • 19
  • 33

2 Answers2

4

They are called as annonymous classes

They enable you to declare and instantiate a class at the same time.

Edit :

They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

SomeOtherName is an instance of an anonymous class that implements the SomeInterface interface.

Mureinik
  • 297,002
  • 52
  • 306
  • 350