繁体   English   中英

在匿名类中使用最终字段,在方法内声明静态嵌套类,并在内部类内定义静态成员

[英]Using Final Fields in Anonymous Classes, Declaring Static Nested Class Inside a Method and Defining Static Members inside an Inner Class

我有三个问题。

1-如果非最终字段的值可以更改,那么如何在非匿名字段类中使用非最终字段?

class Foo{
    private int i;
    void bar(){
        i = 10
        Runnable runnable = new Runnable (){
            public void run (){
                System.out.println(i); //works fine
            }//end method run
        }//end Runnable
    }//end method bar
}//end class Foo 

2-为什么不能在方法内部声明静态嵌套类,因为内部类不能指定(本地类)的名称?

Class Foo {
    void bar(){
        class LocalClass{ //static nested classes are NOT allowed here
            //define members
        }//end class LocalClass
    }//end method bar
}//end class Foo

3-为什么内部类不能定义除静态final字段以外的静态成员?

class Foo {
    class Bar{
        static int x; //NOTallowed
        static final int y; //allowed

        static void doSomething(){} //NOT allowed
    }//end class Bar
}//end class Foo

对于第三个问题,我知道内部类与外部类的实例相关联,但这对我来说仍然没有说服力。 我们可以使用诸如new Foo().Bar.doSomething(); 如果允许使用静态方法。

1-如果非最终字段的值可以更改,那么如何在非匿名字段类中使用非最终字段?

class Foo{
    private int i;
    void bar(){
        i = 10;
        Runnable runnable = new Runnable (){
            public void run (){
                System.out.println(i); //works fine
            }//end method run
        }//end Runnable
    }//end method bar
}//end class Foo 

让我们中断代码等效于-

class Foo{
        private int i;
ublic static void bar() {
    i = 10;
    Runnable r = new ARunnable();
    r.run();
}

private static class ARunnable implements Runnable {

    @Override public void run() {
        System.out.println(i);
    }
}
}

声明的匿名Runnable类本质上是方法bar()的嵌套类,该方法是函数bar()局部类。 因此,匿名类可以访问父类的字段。 但是,如果变量i是函数bar()局部变量,则我们不想允许任何其他函数访问它。 对于方法bar()的内部类函数,我们可以允许对其进行读取但不能对其进行更改,否则它看起来会很奇怪并破坏了local的伦理

class Foo{
   // private int i;
    void bar(){
        final int i = 10;  // adding `final` as i is local to function bar 
        Runnable runnable = new Runnable (){
            public void run (){
                System.out.println(i); 
            }//end method run
        }//end Runnable
    }//end method bar
}/  

2-为什么不能像内部类那样在方法内部声明静态嵌套类?

正如Java规范所说:

紧接在块中的局部类声明的范围(第14.2节)是紧紧包围的块的其余部分,包括它自己的类声明。

如果我们在一个块内声明一个本地类,则它将在封闭的块的上下文中运行。 没有一个块(方法)知道另一个块(方法)的本地实例,因为在一个块内声明的任何内容对于该块都是本地的。 因此,它所在的块(方法)应该是唯一能够实例化它的方法。 将其声明为static毫无意义。 对于class access修饰符privatepublicprotected来说,情况也是如此。

3-为什么内部类不能定义除静态final字段之外的静态成员?

内部类是非静态的。 嵌套的静态类称为嵌套类,而不是内部类。 它在封闭实例的上下文中运行。 不知何故,允许静态变量和方法与这种动机相矛盾。 但是,有关此问题的答案的更多详细说明,请参见此处此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM