Programing

인터페이스 내의 내부 클래스

lottogame 2020. 9. 8. 21:55
반응형

인터페이스 내의 내부 클래스


인터페이스 내에서 내부 클래스를 만들 수 있습니까? 가능하다면 인터페이스 객체를 만들지 않을 것이므로 왜 그런 내부 클래스를 만들고 싶습니까?

이러한 내부 클래스가 개발 프로세스에 도움이됩니까?


예, Java 인터페이스 내부에 중첩 된 클래스 또는 내부 클래스를 모두 만들 있습니다 (일반적인 믿음과는 반대로 " 정적 내부 클래스 " 와 같은 것은 없습니다 . 이것은 단순히 의미가 없으며 "내부"및 "없음"이 없습니다. 중첩 된 클래스가 정적이므로 "정적 내부"가 될 수없는 경우 outter "클래스).

어쨌든 다음은 잘 컴파일됩니다.

public interface A {
    class B {
    }
}

인터페이스 정의에 일종의 "계약 검사기"를 직접 넣는 데 사용되는 것을 보았습니다 (인터페이스에 중첩 된 클래스에서 정적 메서드를 가질 수 있지만 인터페이스 자체와는 반대로). 내가 올바르게 기억하면 이렇게 보입니다.

public interface A {
    static class B {
        public static boolean verifyState( A a ) {
            return (true if object implementing class A looks to be in a valid state)
        }
    }
}

나는 그러한 것의 유용성에 대해 언급하는 것이 아니라 단순히 귀하의 질문에 대답하는 것입니다. 그것은 할 수 있으며 이것은 내가 본 용도 중 하나입니다.

이제 나는 그러한 구조의 유용성에 대해 언급하지 않을 것이며 내가 본 것으로부터 : 나는 그것을 보았지만 그것은 매우 일반적인 구조는 아닙니다.

200KLOC 코드베이스에서 이것이 정확히 제로 시간에 발생합니다 (하지만 우리는 다른 사람들이 완벽하게 정상이라고 생각할 정도로 정확히 제로 시간에 발생하는 나쁜 관행을 고려하는 다른 많은 것들을 가지고 있습니다 ...).


예, 인터페이스 내부에 클래스를 가질 수 있습니다. 사용의 한 가지 예는 다음과 같습니다.

public interface Input
{
    public static class KeyEvent {
         public static final int KEY_DOWN = 0;
         public static final int KEY_UP = 1;
         public int type;
         public int keyCode;
         public char keyChar;
    }
    public static class TouchEvent {
         public static final int TOUCH_DOWN = 0;
         public static final int TOUCH_UP = 1;
         public static final int TOUCH_DRAGGED = 2;
         public int type;
         public int x, y;
         public int pointer;
    }
    public boolean isKeyPressed(int keyCode);
    public boolean isTouchDown(int pointer);
    public int getTouchX(int pointer);
    public int getTouchY(int pointer);
    public float getAccelX();
    public float getAccelY();
    public float getAccelZ();
    public List<KeyEvent> getKeyEvents();
    public List<TouchEvent> getTouchEvents();
}

여기서 코드에는 나중에 getKeyEvents ()와 같은 메서드 정의에서 사용되는 이벤트 객체에 대한 정보를 캡슐화하기위한 두 개의 중첩 클래스가 있습니다. 입력 인터페이스 내부에두면 응집력이 향상됩니다.


IMHO라는 유효한 용도는 둘러싸는 인터페이스 메서드에서 수신하거나 반환하는 개체를 정의하는 것입니다. Tiply 데이터 보유 구조. 이런 식으로 객체가 해당 인터페이스에만 사용되는 경우 더 일관된 방식으로 작업을 수행 할 수 있습니다.

예를 들어 :

interface UserChecker {
   Ticket validateUser(Credentials credentials);

   class Credentials {
      // user and password
   }

   class Ticket {
      // some obscure implementation
   }
}

하지만 어쨌든 ... 그것은 단지 맛의 문제입니다.


Java 7 사양 에서 인용 :

인터페이스에는 멤버 형식 선언 (§8.5)이 포함될 수 있습니다.

인터페이스의 멤버 형식 선언은 암시 적으로 정적이며 공용입니다. 이러한 수정 자 중 하나 또는 둘 다를 중복으로 지정할 수 있습니다.

It is NOT possible to declare non-static classes inside a Java interface, which makes sense to me.


An interesting use case is to provide sort of a default implementation to interface methods through an inner class as described here: https://stackoverflow.com/a/3442218/454667 (to overcome the problem of single-class-inheritance).


It certainly is possible, and one case where I've found it useful is when an interface has to throw custom exceptions. You the keep the exceptions with their associated interface, which I think is often neater than littering your source tree with heaps of trivial exception files.

interface MyInterface {

   public static class MyInterfaceException extends Exception {
   }

   void doSomething() throws MyInterfaceException;
}

Yes it is possible to have static class definitions inside an interface, but maybe the most useful aspect of this feature is when using enum types (which are special kind of static classes). For example you can have something like this:

public interface User {
    public enum Role {
        ADMIN("administrator"),
        EDITOR("editor"),
        VANILLA("regular user");

        private String description;

        private Role(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }

    public String getName();
    public void setName(String name);
    public Role getRole();
    public void setRole(Role role);
    ...
}

What @Bachi mentions is similar to traits in Scala and are actually implemented using a nested class inside an interface. This can be simulated in Java. See also java traits or mixins pattern?


Maybe when you want more complex constructions like some different implementation behaviours, consider:

public interface A {
    public void foo();

    public static class B implements A {
        @Override
        public void foo() {
            System.out.println("B foo");
        }
    }
}

This is your interface and this will be the implementee:

public class C implements A {
    @Override
    public void foo() {
        A.B b = new A.B();
        b.foo(); 
    }

    public static void main(String[] strings) {
        C c = new C();
        c.foo();
    }
}

May provide some static implementations, but won't that be confusing, I don't know.


I found a use fir this type of construct.

  1. You can use this construct to defines and group all the static final constants.
  2. Since, it is an interface you can implement this on an class.

You have access to all the constants grouped; name of the class acts as a namespace in this case.


You can also create "Helper" static classes for common functionality for the objects that implement this interface:

public interface A {
    static class Helper {
        public static void commonlyUsedMethod( A a ) {
           ...
        }
    }
}

I'm needing one right now. I have an interface where it would be convenient to return a unique class from several of it's methods. This class only makes sense as a container for responses from methods of this interface.

Hence, it would be convenient to have a static nested class definition, which is associated only with this interface, since this interface should be the only place where this results container class is ever created.


For instance traits (smth like interface with implemented methods) in Groovy. They are compiled to an interface which contains inner class where all methods are implemented.

참고URL : https://stackoverflow.com/questions/2400828/inner-class-within-interface

반응형