接口内的内部类

发布于 2024-08-23 20:13:31 字数 119 浏览 5 评论 0原文

是否可以在接口中创建内部类
如果可能的话为什么我们要创建一个像这样的内部类 我们不打算创建任何接口对象吗?

这些内部类对任何开发过程都有帮助吗?

Is it possible to create an inner class within an interface?
If it is possible why would we want to create an inner class like that since
we are not going to create any interface objects?

Do these inner classes help in any development process?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

江城子 2024-08-30 20:13:32

您还可以为实现此接口的对象创建通用功能的“Helper”静态类:

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

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 ) {
           ...
        }
    }
}
囚你心 2024-08-30 20:13:32

也许当您想要更复杂的构造(例如一些不同的实现行为)时,请考虑:

public interface A {
    public void foo();

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

这是您的接口,这将是实现者:

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();
    }
}

可能提供一些静态实现,但这不会令人困惑,我不知道。

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.

猫弦 2024-08-30 20:13:32

我发现了这种类型的构造的用途。

  1. 您可以使用此构造来定义和分组所有静态最终常量。
  2. 因为它是一个接口,您可以在类上实现它。

您可以访问所有分组的常量;在这种情况下,类的名称充当命名空间。

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.

墨落画卷 2024-08-30 20:13:32

我现在就需要一个。我有一个接口,可以很方便地从它的几个方法返回一个唯一的类。这堂课才有意义
作为此接口的方法响应的容器。

因此,拥有一个仅与该接口关联的静态嵌套类定义会很方便,因为该接口应该是创建该结果容器类的唯一位置。

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.

迷爱 2024-08-30 20:13:32

例如 traits (类似具有实现方法的接口)在 Groovy 中。它们被编译为一个接口,其中包含实现所有方法的内部类。

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.

〆凄凉。 2024-08-30 20:13:31

是的,我们可以在接口中包含类。一个使用示例可以是

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() 等方法定义中使用。将它们放在输入界面中可以提高凝聚力。

Yes, we can have classes inside interfaces. One example of usage could be

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();
}

Here the code has two nested classes which are for encapsulating information about event objects which are later used in method definitions like getKeyEvents(). Having them inside the Input interface improves cohesion.

じее 2024-08-30 20:13:31

是的,您可以在 Java 接口中创建嵌套类或内部类(请注意,与普遍看法相反,不存在“静态内部类”这样的东西:这根本没有意义,当嵌套类是静态时,没有任何“内部”和“外部”类,因此它不能是“静态内部”)。

无论如何,以下内容编译得很好:

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 代码库在这里,这种情况恰好发生在零时间(但是我们还有很多其他的事情,我们认为这些不好的做法也发生在零时间,其他人会发现完全正常,所以......)。

Yes, you can create both a nested class or an inner class inside a Java interface (note that contrarily to popular belief there's no such thing as an "static inner class": this simply makes no sense, there's nothing "inner" and no "outter" class when a nested class is static, so it cannot be "static inner").

Anyway, the following compiles fine:

public interface A {
    class B {
    }
}

I've seen it used to put some kind of "contract checker" directly in the interface definition (well, in the class nested in the interface, that can have static methods, contrarily to the interface itself, which can't). Looking like this if I recall correctly.

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)
        }
    }
}

Note that I'm not commenting on the usefulness of such a thing, I'm simply answering your question: it can be done and this is one kind of use I've seen made of it.

Now I won't comment on the usefulness of such a construct and from I've seen: I've seen it, but it's not a very common construct.

200KLOC codebase here where this happens exactly zero time (but then we've got a lot of other things that we consider bad practices that happen exactly zero time too that other people would find perfectly normal so...).

渡你暖光 2024-08-30 20:13:31

恕我直言,有效的用途是定义由封闭接口方法接收或返回的对象。通常是数据保存结构。这样,如果该对象仅用于该接口,那么您就会以更具凝聚力的方式获得事物。

举例来说:

interface UserChecker {
   Ticket validateUser(Credentials credentials);

   class Credentials {
      // user and password
   }

   class Ticket {
      // some obscure implementation
   }
}

但无论如何......这只是一个品味问题。

A valid use, IMHO, is defining objects that are received or returned by the enclosing interface methods. Tipically data holding structures. In that way, if the object is only used for that interface, you have things in a more cohesive way.

By example:

interface UserChecker {
   Ticket validateUser(Credentials credentials);

   class Credentials {
      // user and password
   }

   class Ticket {
      // some obscure implementation
   }
}

But anyway... it's only a matter of taste.

以可爱出名 2024-08-30 20:13:31

引自 Java 7 规范

接口可以包含成员类型声明(第 8.5 节)。

接口中的成员类型声明是隐式静态和公共的。允许冗余地指定其中一个或两个修饰符。

在 Java 接口中声明非静态类是不可能的,这对我来说很有意义。

Quote from the Java 7 spec:

Interfaces may contain member type declarations (§8.5).

A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.

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

゛时过境迁 2024-08-30 20:13:31

一个有趣的用例是通过内部类为接口方法提供某种默认实现,如下所述:https://stackoverflow.com /a/3442218/454667(克服单类继承的问题)。

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).

绮烟 2024-08-30 20:13:31

是的,接口内可以有静态类定义,但也许此功能最有用的方面是使用枚举类型(这是一种特殊的静态类)。例如你可以有这样的东西:

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);
    ...
}

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);
    ...
}
青朷 2024-08-30 20:13:31

这当然是可能的,我发现它有用的一种情况是当接口必须抛出自定义异常时。您可以将异常与其关联的接口一起保留,我认为这通常比在源代码树中堆放大量琐碎的异常文件更整洁。

interface MyInterface {

   public static class MyInterfaceException extends Exception {
   }

   void doSomething() throws MyInterfaceException;
}

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;
}
夜深人未静 2024-08-30 20:13:31

@Bachi 提到的与 Scala 中的特征类似,实际上是使用接口内的嵌套类来实现的。这可以用Java 来模拟。另请参阅 java 特征还是 mixins 模式?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文