Practical side of the ability to define a class within an interface in Java?

前端 未结 11 1309
暖寄归人
暖寄归人 2020-12-30 06:32

What would be the practical side of the ability to define a class within an interface in Java:

interface IFoo
{
    class Bar
    {
        void foobar (         


        
11条回答
  •  醉酒成梦
    2020-12-30 07:26

    With a static class inside an interface you have the possibility to shorten a common programming fragment: Checking if an object is an instance of an interface, and if so calling a method of this interface. Look at this example:

    public interface Printable {
        void print();
    
        public static class Caller {
            public static void print(Object mightBePrintable) {
                if (mightBePrintable instanceof Printable) {
                    ((Printable) mightBePrintable).print();
                }
            }
        }
    }
    

    Now instead of doing this:

    void genericPrintMethod(Object obj) {
        if (obj instanceof Printable) {
            ((Printable) obj).print();
        }
    }
    

    You can write:

    void genericPrintMethod(Object obj) {
       Printable.Caller.print(obj);
    }
    

提交回复
热议问题