簡體   English   中英

接口的靜態字段和最終字段的含義

[英]Meaning of static and final fields of an interface

受“ 接口與抽象類 ”問題和公認的答案的激勵,我想得到一個更詳細,更明確的答案。 特別是我無法理解“接口中的字段是隱式靜態且是最終的”這一說法。 這是否意味着實現包含方法foo()的接口的類A可以將方法作為A.foo()調用?

關於final的問題:只要接口僅包含方法,給定一個抽象類A使用方法foo()實現一個接口,而普通class B擴展了abstract class A ,則class B不能覆蓋foo方法嗎? 就我而言,最終方法是不可能被覆蓋的。 到底是什么?

“接口中的字段是隱式靜態且是最終的”。

在界面上寫

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();

接口都一樣。

就我而言,最終方法不可能被覆蓋

final實例方法不能被覆蓋,final靜態方法不能被隱藏。

同樣,嵌套的接口,類和注釋是公共的和靜態的。 嵌套的接口和注釋也隱式抽象。

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

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

它在談論領域 字段不是方法。

這是否意味着實現包含方法foo()的接口的類A可以將方法作為A.foo()調用?

不,您需要使用new創建A的實例,然后在該實例上實現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?

接口方法不能是最終的,所以這個問題沒有道理。 實現接口的抽象類的子類可以為接口方法提供自己的實現。

嘗試看看這個。

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();
    }
}
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.

接口中的每個字段都是公共的,靜態的和最終的,因為...

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.

表示方法在接口中不是最終的。

有關更多詳細信息,請通過本教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM