嵌套静态类Java [英] Nested Static classes Java

查看:62
本文介绍了嵌套静态类Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者.运行给定的问题时,我正在练习Java嵌套类.我正在使用Oracle JDK 11.0.5.

I am a beginner to Java. I was practising Java nested classes when I run the given problem. I am using Oracle JDK 11.0.5.

问题:每当我尝试为以下代码运行编译器时,都会遇到给定的错误.

Problem: whenever I try to run the compiler for the following code I run across the given errors.

public class test {

    public class Outer{
        static int out1;    

        public static void display1() {
            System.out.println("\n\nIn outer one!");
            System.out.println(out1);       
        }

        public static class Inner{
            static int ini;
            static String ins;
            static char inc;
            static float inf;

            static {
                ini = 2;
                ins = "Inner";
                inc = 'I';
                inf = 2.0f;
            }

            public static void display2() {
                System.out.println("In the inner class now!");
                System.out.println(ini);
                System.out.println(ins);
                System.out.println(inc);
                System.out.println(inf);
            }

        }
    }

    public static void main(String[] args) {

        Outer o1 = new Outer();
        o1.Inner.display2();
    }
}

错误:

但是,当我在第1行中添加static关键字以使其成为"public static class Outer"并且没有其他更改时,代码开始正常工作.为什么?是因为静态成员无法访问非静态数据吗?

But when I add the static keyword in line-1 to make it "public static class Outer" and no other changes, the code started working fine. Why is it? Is it because static members can't access non-static data?

推荐答案

public class test {
    public class Outer{
    }

    public static void main(String[] args) {
        Outer o1 = new Outer();

Outer需要引用test.this.您需要使用高度模糊​​的语法为构造函数提供对test实例的引用,希望您在实际代码中永远不会看到.

Outer requires a reference to test.this. You would need to supply a reference to an instance of test to the constructor with the highly obscure syntax that hopefully you will never see in real code.

对于非静态内部类的静态成员有模糊的限制.这些细节太无聊了,难以记住.就在前几天,它被讨论了放松一下,就好像Java不允许您在此区域进行足够愚蠢的事情一样.

There are obscure restrictions regarding static members of non-static inner classes. The details are too boring to remember. Just the other day it was mooted that this be relaxed, as if Java didn't allow you to enough silly things in this area already.

        o1.Inner.display2();

由于Inner是静态嵌套类,因此在这里未将ol用作实例.令人惊讶的是,它被用于其静态类型,并且可以替换为Outer.

As Inner is a static nested class ol isn't being used as an instance here. Surprisingly it is being used for its static type and could be replaced by Outer.

我的建议是尝试避免嵌套/内部/本地类,并绝对避免任何可变的静态变量(即全局状态).

My advice would be to try to avoid nested/inner/local classes and definitely avoid any mutable statics (i.e. global state).

这篇关于嵌套静态类Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆