Java - 接口的非静态成员变量
Java - non static member variable of an interface
我知道不推荐,但是为什么我可以声明一个接口的成员变量不是静态的呢?
接口的静态成员和非静态成员有什么区别?我看到如果我将一个接口成员变量定义为静态的,我可以以非静态的方式在实现 class 中使用它:
接口:
public interface Pinuz {
final static int a;
public void method1();
}
实施class:
public class Test implements Pinuz {
public static void main(String[] args) {
Test t = new Test();
int b = t.a;
}
@Override
public void method1() {
// TODO Auto-generated method stub
}
}
我只看到一条警告,要求我以静态方式使用成员 a。
Why can I declare a member variable of an interface not static?
隐含地static
(和final
)(这意味着它是static
,即使你省略了static
关键字), as stated in the JLS:
Every field declaration in the body of an interface is implicitly public
, static
, and final
. It is permitted to redundantly specify any or all of these modifiers for such fields.
最终的原因是任何实现都可以更改成员的值,如果它没有定义为 final
。然后该成员将成为实现的一部分,但正如您所知,interface
是一个纯粹的抽象。
之所以static
是因为成员属于接口,而不是实现实例。
此外,作为 static
,你应该只用 class-name 引用它(否则你会收到编译器警告),而不是通过一些引用,所以 int b = t.a;
应该是刚写成 int b = Test.a;
您不能在 Java 接口中声明非静态变量。
接口中的每个变量都是隐式的 public、静态的和最终的。
一个接口的所有成员变量,无论你是否声明为静态的,都是静态的
我知道不推荐,但是为什么我可以声明一个接口的成员变量不是静态的呢?
接口的静态成员和非静态成员有什么区别?我看到如果我将一个接口成员变量定义为静态的,我可以以非静态的方式在实现 class 中使用它:
接口:
public interface Pinuz {
final static int a;
public void method1();
}
实施class:
public class Test implements Pinuz {
public static void main(String[] args) {
Test t = new Test();
int b = t.a;
}
@Override
public void method1() {
// TODO Auto-generated method stub
}
}
我只看到一条警告,要求我以静态方式使用成员 a。
Why can I declare a member variable of an interface not static?
隐含地static
(和final
)(这意味着它是static
,即使你省略了static
关键字), as stated in the JLS:
Every field declaration in the body of an interface is implicitly
public
,static
, andfinal
. It is permitted to redundantly specify any or all of these modifiers for such fields.
最终的原因是任何实现都可以更改成员的值,如果它没有定义为 final
。然后该成员将成为实现的一部分,但正如您所知,interface
是一个纯粹的抽象。
之所以static
是因为成员属于接口,而不是实现实例。
此外,作为 static
,你应该只用 class-name 引用它(否则你会收到编译器警告),而不是通过一些引用,所以 int b = t.a;
应该是刚写成 int b = Test.a;
您不能在 Java 接口中声明非静态变量。 接口中的每个变量都是隐式的 public、静态的和最终的。
一个接口的所有成员变量,无论你是否声明为静态的,都是静态的