首页 技术 正文
技术 2022年11月14日
0 收藏 826 点赞 4,142 浏览 7126 个字

Nested classes are further divided into two types:

  1. static nested classes: If the nested class is static, then it’s called static nested class. Static nested classes can access only static members of the outer class. Static nested class is same as any other top-level class and is nested for only packaging convenience.

    Static class object can be created with following statement:

    12 OuterClass.StaticNestedClass nestedObject =     new OuterClass.StaticNestedClass();

    静态嵌套类:如果嵌套类是静态的,则称作静态嵌套类。静态嵌套类只能访问外部类的静态成员。

  2. java inner class: Any non-static nested class is known as inner class. Inner classes are 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 instance, we can’t have any static variables in them. Object of inner class are part of the outer class object and to create an instance of inner class, we first need to create instance of outer class.

    Inner classes can be instantiated like this:

    12 OuterClass outerObject = new OuterClass();OuterClass.InnerClass innerObject = outerObject.new InnerClass();

There are two special kinds of java inner classes.

  1. local inner class: If a class is defined in a method body, it’s known as local inner class. Since local inner class is not associated with Object, we can’t use private, public or protected access modifiers with it. The only allowed modifiers are abstract or final. A local inner class can access all the members of the enclosing class and local final variables in the scope it’s defined.

    Local inner class can be defined as:

    1234567 public void print() {        //local inner class inside the method        class Logger {            String name;        }        //instantiate local inner class in the method to use        Logger logger = new Logger();
  2. anonymous inner class: A local inner class without name is known as anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface. Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.
    It’s a bit hard to define how to create anonymous inner class, we will see it’s real time usage in test program below.

Here is a java class showing how to define java inner class, static nested class, local inner class and anonymous inner class.

 

OuterClass.java
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 package com.journaldev.nested;  import java.io.File;import java.io.FilenameFilter;  public class OuterClass {         private static String name = "OuterClass";    private int i;    protected int j;    int k;    public int l;     //OuterClass constructor    public OuterClass(int i, int j, int k, int l) {        this.i = i;        this.j = j;        this.k = k;        this.l = l;    }      public int getI() {        return this.i;    }      //static nested class, can access OuterClass static variables/methods    static class StaticNestedClass {        private int a;        protected int b;        int c;        public int d;          public int getA() {            return this.a;        }          public String getName() {            return name;        }    }      //inner class, non static and can access all the variables/methods of outer class    class InnerClass {        private int w;        protected int x;        int y;        public int z;          public int getW() {            return this.w;        }          public void setValues() {            this.w = i;            this.x = j;            this.y = k;            this.z = l;        }          @Override        public String toString() {            return "w=" + w + ":x=" + x + ":y=" + y + ":z=" + z;        }          public String getName() {            return name;        }    }      //local inner class    public void print(String initial) {        //local inner class inside the method        class Logger {            String name;              public Logger(String name) {                this.name = name;            }              public void log(String str) {                System.out.println(this.name + ": " + str);            }        }         Logger logger = new Logger(initial);        logger.log(name);        logger.log("" + this.i);        logger.log("" + this.j);        logger.log("" + this.k);        logger.log("" + this.l);    }      //anonymous inner class    public String[] getFilesInDir(String dir, final String ext) {        File file = new File(dir);        //anonymous inner class implementing FilenameFilter interface        String[] filesList = file.list(new FilenameFilter() {             @Override            public boolean accept(File dir, String name) {                return name.endsWith(ext);            }         });        return filesList;    }}

Here is the test program showing how to instantiate and use nested class in java.

NestedClassTest.java
1234567891011121314151617181920212223242526272829303132333435363738 package com.journaldev.nested; import java.util.Arrays;//nested classes can be used in import for easy instantiationimport com.journaldev.nested.OuterClass.InnerClass;import com.journaldev.nested.OuterClass.StaticNestedClass; public class NestedClassTest {     public static void main(String[] args) {        OuterClass outer = new OuterClass(1,2,3,4);                 //static nested classes example        StaticNestedClass staticNestedClass = new StaticNestedClass();        StaticNestedClass staticNestedClass1 = new StaticNestedClass();                 System.out.println(staticNestedClass.getName());        staticNestedClass.d=10;        System.out.println(staticNestedClass.d);        System.out.println(staticNestedClass1.d);                 //inner class example        InnerClass innerClass = outer.new InnerClass();        System.out.println(innerClass.getName());        System.out.println(innerClass);        innerClass.setValues();        System.out.println(innerClass);                 //calling method using local inner class        outer.print("Outer");                 //calling method using anonymous inner class        System.out.println(Arrays.toString(outer.getFilesInDir("src/com/journaldev/nested", ".java")));                 System.out.println(Arrays.toString(outer.getFilesInDir("bin/com/journaldev/nested", ".class")));    } }

Here is the output of above program:

12345678910111213 OuterClass100OuterClassw=0:x=0:y=0:z=0w=1:x=2:y=3:z=4Outer: OuterClassOuter: 1Outer: 2Outer: 3Outer: 4[NestedClassTest.java, OuterClass.java][NestedClassTest.class, OuterClass$1.class, OuterClass$1Logger.class, OuterClass$InnerClass.class, OuterClass$StaticNestedClass.class, OuterClass.class]

Notice that when OuterClass is compiled, separate class files are created for inner class, local inner class and static nested class.

Benefits of Java Nested Class

  1. If a class is useful to only one class, it makes sense to keep it nested and together. It helps in packaging of the classes.
  2. Nested classes increases encapsulation. Note that inner classes can access outer class private members and at the same time we can hide inner class from outer world.
  3. Nesting small classes within top-level classes places the code closer to where it is used and makes code more readable and maintainable.

Hungry for More? Check out these amazing posts:

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,994
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,507
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,350
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,135
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,768
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,845