Java 内部类

Java内部类可以被宣布为私有、公共、受保护或默认访问,而外部类只能具有公共或默认访问。

  1. static nested class

    If the nested class is static, then it's called a static nested class. Static nested classes can access only static members of the outer class. A static nested class is the same as any other top-level class and is nested for only packaging convenience. A static class object can be created with the following statement.``` OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
  2. java inner class

    java inner class Any non-static nested class is known as inner class in java. Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can't have any static variables in them. The object of java inner class are part of the outer class object and to create an instance of the inner class, we first need to create an instance of outer class. Java inner class can be instantiated like this;``` OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new InnerClass();

有两种特殊类型的Java内部类。

  1. 联合国 本地内科( ) (英语). 如果某类在方法体中被定义,则被称为"本地内类". 由于本地的内科与Object没有关联,我们不能使用私人,公共或被保护的接入修饰器与之相接. 唯一允许的修饰者为抽象或最终. 本地的内层阶级可以访问所定义范围内的附加类的所有成员和本地最终变量. 此外,它也可以访问定义方法的非最终本地变量,但不能修改. 因此,如果您尝试打印非最终本地变量的值,它将被允许,但如果您试图从内部方法本地内层类中更改其值,您将会得到编译时间错误。 本地内层分类可以被定义为:_____ 套件 com.journaldev.innerclass; (- ) (- ) 公用类主类 {(- ) (- ) 私用字符串 s_main_class; (- ) 公用字印 (-) {(- ) 字符串 s_print_method; (- ) / 本地内层分类 方法 {(- bR publo) s-(-MBR1_ publo_ public) 。 下面的代码会扔出编译时间错误: // 附加范围内定义的本地可变 s_print_方法必须是最终或有效的 final /// s_print_method= ":"; (- )} (- )} (- ) // 即时 本地内层类在使用方法中必须使用 (- ) Logger logger = new Logger (); (- )}(- ) (- ) 我们也可以定义任何区块内的本地内层类,如静态区块等,如果-else区块等. 然而,在这种情况下,该类的范围将非常有限. ^ 公共类 MainClass { (- ) (- ) 静态 { (- ) 类 Foo { (- ) (- ) oo (- ) (- ) 公共空白栏 (-) { 如果 (1 < 2) { 类测试 {

测试 t1 = 新测试 (); } // 下面会因为类的范围而丢出错误( _) ) //t测试=新测试 (; (- ) //Foo f=新Foo (; (- )} (- )} (- ) ``` (- ) 2. ### 匿名内课 (-). ),当地一个没有名字的内科班被称为匿名内科班. 匿名类在单个语句中被定义并即时化. 匿名内课总是扩展一个类或执行接口. 由于匿名类没有名字,因此不可能为匿名类定义一个构建者. 匿名的内课只有在定义时才能进入. 很难定义如何创建匿名的内课,我们可以看到下面的测试程序是实时使用. (单位:千美元) (英语)

这里有一个 Java 类,说明如何定义 Java 内部类、静态嵌入类、本地内部类和匿名内部类。

  1package com.journaldev.nested;
  2
  3import java.io.File;
  4import java.io.FilenameFilter;
  5
  6public class OuterClass {
  7
  8    private static String name = "OuterClass";
  9    private int i;
 10    protected int j;
 11    int k;
 12    public int l;
 13
 14    //OuterClass constructor
 15    public OuterClass(int i, int j, int k, int l) {
 16        this.i = i;
 17        this.j = j;
 18        this.k = k;
 19        this.l = l;
 20    }
 21
 22    public int getI() {
 23        return this.i;
 24    }
 25
 26    //static nested class, can access OuterClass static variables/methods
 27    static class StaticNestedClass {
 28        private int a;
 29        protected int b;
 30        int c;
 31        public int d;
 32
 33        public int getA() {
 34            return this.a;
 35        }
 36
 37        public String getName() {
 38            return name;
 39        }
 40    }
 41
 42    //inner class, non-static and can access all the variables/methods of the outer class
 43    class InnerClass {
 44        private int w;
 45        protected int x;
 46        int y;
 47        public int z;
 48
 49        public int getW() {
 50            return this.w;
 51        }
 52
 53        public void setValues() {
 54            this.w = i;
 55            this.x = j;
 56            this.y = k;
 57            this.z = l;
 58        }
 59
 60        @Override
 61        public String toString() {
 62            return "w=" + w + ":x=" + x + ":y=" + y + ":z=" + z;
 63        }
 64
 65        public String getName() {
 66            return name;
 67        }
 68    }
 69
 70    //local inner class
 71    public void print(String initial) {
 72        //local inner class inside the method
 73        class Logger {
 74            String name;
 75
 76            public Logger(String name) {
 77                this.name = name;
 78            }
 79
 80            public void log(String str) {
 81                System.out.println(this.name + ": " + str);
 82            }
 83        }
 84
 85        Logger logger = new Logger(initial);
 86        logger.log(name);
 87        logger.log("" + this.i);
 88        logger.log("" + this.j);
 89        logger.log("" + this.k);
 90        logger.log("" + this.l);
 91    }
 92
 93    //anonymous inner class
 94    public String[] getFilesInDir(String dir, final String ext) {
 95        File file = new File(dir);
 96        //anonymous inner class implementing FilenameFilter interface
 97        String[] filesList = file.list(new FilenameFilter() {
 98
 99            @Override
100            public boolean accept(File dir, String name) {
101                return name.endsWith(ext);
102            }
103
104        });
105        return filesList;
106    }
107}

以下是测试程序,展示如何在java中实例化和使用内部类。

 1package com.journaldev.nested;
 2
 3import java.util.Arrays;
 4//nested classes can be used in import for easy instantiation
 5import com.journaldev.nested.OuterClass.InnerClass;
 6import com.journaldev.nested.OuterClass.StaticNestedClass;
 7
 8public class InnerClassTest {
 9
10    public static void main(String[] args) {
11        OuterClass outer = new OuterClass(1,2,3,4);
12
13        //static nested classes example
14        StaticNestedClass staticNestedClass = new StaticNestedClass();
15        StaticNestedClass staticNestedClass1 = new StaticNestedClass();
16
17        System.out.println(staticNestedClass.getName());
18        staticNestedClass.d=10;
19        System.out.println(staticNestedClass.d);
20        System.out.println(staticNestedClass1.d);
21
22        //inner class example
23        InnerClass innerClass = outer.new InnerClass();
24        System.out.println(innerClass.getName());
25        System.out.println(innerClass);
26        innerClass.setValues();
27        System.out.println(innerClass);
28
29        //calling method using local inner class
30        outer.print("Outer");
31
32        //calling method using anonymous inner class
33        System.out.println(Arrays.toString(outer.getFilesInDir("src/com/journaldev/nested", ".java")));
34
35        System.out.println(Arrays.toString(outer.getFilesInDir("bin/com/journaldev/nested", ".class")));
36    }
37
38}

以下是上面的Java内部类示例程序的输出。

 1OuterClass
 210
 30
 4OuterClass
 5w=0:x=0:y=0:z=0
 6w=1:x=2:y=3:z=4
 7Outer: OuterClass
 8Outer: 1
 9Outer: 2
10Outer: 3
11Outer: 4
12[NestedClassTest.java, OuterClass.java]
13[NestedClassTest.class, OuterClass$1.class, OuterClass$1Logger.class, OuterClass$InnerClass.class, OuterClass$StaticNestedClass.class, OuterClass.class]

请注意,当 OuterClass 编译时,将为内部类、本地内部类和静态嵌入类创建单独的类文件。

Java内部类的优点

如果一个类只对一个类有用,那么把它固定在一起有意义。它有助于类的包装 2.Java内部类实现了封装。请注意,内部类可以访问外部类的私人成员,同时我们可以从外部世界隐藏内部类 3.在顶级类内保持小类使代码更接近使用的地方,使代码更易读和可维护

对于Java内部类来说,这就是全部。

Published At
Categories with 技术
Tagged with
comments powered by Disqus