Java教程

Java嵌套接口

在另一个接口或类中声明的接口称为嵌套接口。嵌套接口用于对相关接口进行分组,以便于维护。嵌套接口必须由外部接口或类引用。不能直接访问它。

嵌套接口要记住的要点

给出了一些Java程序员应该记住的要点。
嵌套接口如果在接口内声明,则必须是公共的,但如果在类中声明,则可以具有任何访问修饰符。 嵌套接口被隐式声明为静态。

在接口内声明的嵌套接口的语法

interface interface_name{
    ... interface nested_interface_name{
    ... }
}

在类中声明的嵌套接口的语法

class class_name{
    ... interface nested_interface_name{
    ... }
}

在接口内声明的嵌套接口示例

在此示例中,我们将学习如何声明嵌套接口以及如何访问它。
interface Showable{
    void show();
    interface Message{
        void msg();
    }
}
class TestNestedInterface1 implements Showable.Message{
    public void msg(){
        System.out.println("Hello nested interface");
    }
    public static void main(String args[]){
        Showable.Message message=new TestNestedInterface1();
        //upcasting here message.msg();
    }
}
Output:hello nested interface
如您在上面的示例中看到的,我们正在通过其外部接口Showable来访问Message接口,因为它不能直接访问。就像房间里的Almirah,我们不能直接进入Almirah,因为我们必须先进入房间。在集合框架中,sun microsystem提供了一个嵌套的接口Entry。 Entry是Map的子接口,即可以通过Map.Entry访问。

由Java编译器为嵌套接口Message生成的内部代码

java编译器在内部创建公共和静态接口,如下所示: 。
public static interface Showable$Message {
    public abstract void msg();
}

在类中声明的嵌套接口的示例

让我们看看如何在类内部定义接口以及如何访问它。
class A{
    interface Message{
        void msg();
    }
}
class TestNestedInterface2 implements A.Message{
    public void msg(){
        System.out.println("Hello nested interface");
    }
    public static void main(String args[]){
        A.Message message=new TestNestedInterface2();
        //upcasting here message.msg();
    }
}
Output:hello nested interface

我们可以在接口内部定义一个类吗?

是的,如果我们在接口内部定义一个类,则Java编译器会创建一个静态嵌套类。让我们看看如何在接口内定义一个类:
interface M{
    class A{
    }
}
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4