2015-11-07 72 views
0

我正在爲樹形數據結構編寫幾個接口。我得到 Cannot make a static reference to the non-static type E編譯錯誤。無法對靜態類型進行靜態引用E

這裏是我的接口層次:

package com.mohit.dsa.global.position; 

/** 
* @author mohitkum 
*/ 
public interface Position<E> { 
    public E getElement() throws IllegalStateException; 
} 

-

package com.mohit.dsa.tree; 

import com.mohit.dsa.global.position.Position; 

public interface Tree<E> extends Iterable<E> { 
    Position<E> root;//compilation error for E 
} 

這將是巨大的,如果有人能解釋這個錯誤的原因。

回答

2

當你在一個接口中有一個字段時,它是public static final。因此Position root;(即使沒有泛型)在接口中無效。進一步假設你正在初始化最終的字段根目錄,並說你的樹接口實現爲:

class A1 implements Tree<A> 

class B1 implements Tree<B> 

這將成爲一個問題吧?因爲這將轉化:

Position<A>根在一種情況下 Position<B>根在另一種情況下

,但你的領域是最後所以這個斜面工作。

以下線程相關: Java - An interface that has static field pointing to class name of its sub class?

相關問題