|NO.Z.00077|——————————|BigDataEnd|——|Java&特殊类.V05|——|Java.v05|静态内部类.v02|使用方式|

一、静态内部类的使用方式
### --- 静态内部类的使用方式

~~~     ——>        静态内部类不能直接访问外部类的非静态成员。
~~~     ——>        静态内部类可以直接创建对象。
~~~     ——>        如果静态内部类访问外部类中与本类内同名的成员变量或方法时,
~~~     ——>        需要使用类名.的方式访问。
二、编程代码
package com.yanqi.task10;

/**
 * 实现静态内部类的定义和使用
 */
public class StaticOuter {
    private int cnt = 1;        // 隶属于对象层级
    private static int snt = 2; // 隶属于类层级

    public /*static*/ void show() {
        System.out.println("外部类的show方法就是这里!");
    }

    /**
     * 定义静态内部类   有static关键字修饰隶属于类层级
     */
    public static class StaticInner {
        private int ia = 3;
        private static int snt = 4;

        public StaticInner() {
            System.out.println("静态内部类的构造方法哦!");
        }

        public void show() {
            System.out.println("ia = " + ia); // 3
            System.out.println("外部类中的snt = " + snt); // 2
            //System.out.println("外部类的cnt = " + cnt); // Error:静态上下文中不能访问非静态的成员,因此此时可能还没有创建对象
        }

        public void show2(int snt) {  // 就近原则
            System.out.println("snt = " + snt); // 5
            System.out.println("内部类中的成员snt = " + StaticInner.snt); // 4
            System.out.println("外部类中的成员snt = " + StaticOuter.snt); // 2
            //StaticOuter.show();
            new StaticOuter().show();
        }
    }
}
三、编程代码
package com.yanqi.task10;

public class StaticOuterTest {

    public static void main(String[] args) {

        // 1.声明StaticInner类型的引用指向该类型的对象
        StaticOuter.StaticInner si = new StaticOuter.StaticInner();
        // 2.调用show方法进行测试
        si.show();

        System.out.println("---------------------------------------------");
        si.show2(5);
    }
}
四、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=54119:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task10.StaticOuterTest
静态内部类的构造方法哦!
ia = 3
外部类中的snt = 4
---------------------------------------------
snt = 5
内部类中的成员snt = 4
外部类中的成员snt = 2
外部类的show方法就是这里!

Process finished with exit code 0

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

 

posted on 2022-04-03 18:05  yanqi_vip  阅读(22)  评论(0)    收藏  举报

导航