为什么我不能在内部类中声明和初始化静态变量? [英] Why can't I declare and initialize static variable in inner class?

查看:111
本文介绍了为什么我不能在内部类中声明和初始化静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A类是外部类。 B类是A的内部类,C类是B的内部类。



所有三个类声明并初始化一个静态最终变量。



这是A类中的对象:

  static final Object x = new Object ); 

B类:

  static final Object x1 = new Object(); 

class C:

  static final Object x2 = new Object();问题是,A类中的变量编译得很好,但是在B和C中,变量不是。 



错误讯息:


不声明静态;静态字段只在
中声明静态和顶级类型


String ,并且类B和C中的 int 没有收到错误。



完成代码: p>

  class A {
static final Object x = new Object();
static final String s =s1;
static final int y = 1;

类B {
static final Object x1 = new Object();
static final String s1 =s1;
static final int y1 = 1;

class C {
static final Object x2 = new Object();
static final String s2 =s1;
static final int y2 = 1;
}
}
}


解决方案>

在常规内部类中不能有静态字段/方法,因为内部类只适用于外部类的实例。





但它们可以有编译时常量,检查 JLS 8.1.3 。您 x x1 x2 s1 s2 y1 y2 是编译时常数


内部类不能声明静态初始化
接口或编译时错误。



内部类不能声明静态成员,除非它们是常量变量(§4.12.4 )或发生编译时错误。



class A is the outer class. Class B is an inner class of A, and class C is an inner class of B.

All three classes declare and initialize one static final variable.

This is the object in class A:

static final Object x = new Object();

class B:

static final Object x1 = new Object();

class C:

static final Object x2 = new Object();

The problem is that the variable in class A compiles fine, but in B and C the variable does not.

Error message:

the field can not be declare static; static field only declared in static and top level type

The String, and int in class B and C doesn't receive an error.

Complete code:

class A {
  static final Object x = new Object();
  static final String s = "s1";
  static final int y = 1;

  class B {
    static final Object x1 = new Object();
    static final String s1 = "s1";
    static final int y1 = 1;

     class C {
      static final Object x2 = new Object();
      static final String s2 = "s1";
      static final int y2 = 1;
     }
  }
}

解决方案

You can't have static fields/method in a regular inner classes, because, inner classes will work only with instance of outer classes.

So, static can't be there with instances.

But they can have compile time constants, check JLS 8.1.3. You x, x1, x2 are not compile time constants, while s1, s2, y1, y2 are compile time constants

Inner classes may not declare static initializers (§8.7) or member interfaces, or a compile-time error occurs.

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.

这篇关于为什么我不能在内部类中声明和初始化静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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