接口的静态和最终字段的含义

时间:2012-08-31 13:35:22

标签: java interface static final

受问题Interface vs Abstract Classes和接受的答案的刺激,我希望得到更详细和澄清的答案。特别是我无法理解语句“接口中的字段是隐式静态和最终的”。是否意味着实现包含方法foo()的接口的类A可以将该方法调用为A.foo()

关于final的内容:只要接口只包含方法,给定一个实现具有方法foo()的接口的抽象类A和一个扩展class B的普通abstract class Aclass B覆盖foo方法?就我而言,最终的方法是不可能被覆盖的。最后真的是什么?

5 个答案:

答案 0 :(得分:7)

  

“接口中的字段隐式静态且最终”。

在界面写作

int N = 1;
public int N = 1;
static int N = 1;
public static int N = 1;
// also
final int N = 1;
public final int N = 1;
static final int N = 1;
public static final int N = 1;

都是一样的。

  

这是否意味着实现包含方法foo()的接口的类A可以调用该方法为A.foo()

字段和方法都是成员,但方法和字段不是一回事。

界面中的方法不能是staticfinal,而是隐式公开和抽象的

int foo();
public int foo();
abstract int foo();
public abstract int foo();
接口的

都是一样的。

  

就我而言,最终方法无法被覆盖

无法覆盖最终实例方法,并且无法隐藏最终的静态方法。

类似地,嵌套的接口,类和注释是公共的和静态的。嵌套接口和注释也是隐式抽象的。

interface A {
    public static class C { }
    public static /* final */ enum E {; }
    public static abstract interface I { }
    public static abstract @interface A { }
}

答案 1 :(得分:0)

  
    

“界面中的字段是......”

  

它正在讨论字段。字段不是方法。

答案 2 :(得分:0)

  

这是否意味着实现包含的接口的A类   方法foo()可以调用方法为A.foo()?

不,您需要使用A创建new的实例,然后在实例上实现foo

 As long as interfaces contain only methods, given an abstract class A which implements an interface with a method foo() and an ordinary class B which extends the abstract class A, cannot the class B override the foo method? As far as I am concerned, final methods are impossible to be overridden. What is true finally?

接口方法不能是最终的,所以这个问题毫无意义。实现接口的抽象类的子类可以为接口方法提供自己的实现。

答案 3 :(得分:0)

试着看看这个。

public interface A {
    int x = 4;
    public void printVal();
}

public class B implements A {

    public void printVal() {
        System.out.println(A.x);
    }

    public static void main(String [] args) {
        System.out.println(A.x);

        (new B()).printVal();
    }
}

答案 4 :(得分:0)

Interface can only contain abstract methods, properties but we don’t
need to put abstract and public keyword. All the methods and properties
defined in Interface are by default public and abstract.

界面中的每个字段都是public,static和final,因为......

Interface variables are static because Java interfaces cannot be instantiated 
in their own right; the value of the variable must be assigned in a static 
context in which no instance exists. The final modifier ensures the value
assigned to the interface variable is a true constant that cannot be 
re-assigned by program code.

例如:

public interface Test
  {
    int value = 3; //it should be same as public static final int value = 3;
  }

如果是接口的成员功能。

A method declaration within an interface is followed by a semicolon,
but no braces, because an interface does not provide implementations
for the methods declared within it. All methods declared in an interface 
are implicitly public, so the public modifier can be omitted.

意味着方法在界面中不是最终的。

有关详细信息,请查看此Tutorial

相关问题