2014-03-28 113 views
0

我試圖覆蓋,看起來有點像這個斯卡拉 - 無法覆蓋Java類

public class ExampleJava { 
    public ExampleJava(String string) { 

    } 

    protected String string; 
} 

當我使用

class ExampleScala(string : String) { 
    @Override 
    protected override def string : String 
} 
在斯卡拉

一個Java類的受保護的變量時,編譯器會發出錯誤:

Error:(5, 7) overriding method string in class ExampleScala of type => 
java.lang.String; 
variable string in class ExampleJava of type net.java.lang.String has incompatible  
type; 
(Note that method string in class ExampleJava of type => java.lang.String is 
abstract, 
and is therefore overridden by concrete variable string in class ExampleJava of type 
java.lang.String) 
class ExampleScala(material : Material) extends ExampleJava(string : String) { 
^

更新:我不能莫迪fy ExampleJava,因爲它在一個程序中被擴展,如果這個被釋放它不會工作

回答

2
  1. 你不斯卡拉使用@Override;只有Java編譯器才知道它。在斯卡拉override被用來代替。

  2. protected String string; in ExampleJava是一個字段,所以它根本不能被覆蓋。如果你希望它是重寫的,你需要寫

    private String string; 
    
    protected String string() { 
        return string; 
    } 
    

代替。您還需要在ExampleScala中實際執行。

+0

任何方式做這樣的事情,而不改變ExampleJava?我不能瓶坯修改ExampleJava因爲它是在正在擴展程序,如果這個被釋放它不會工作。 – yayestechlab

+0

不,根本無法覆蓋字段。你究竟想實現什麼? –

1

你不能@Override字段成員,你只能重寫方法,它只是一個註釋,確保在編譯時天氣你真的覆蓋方法或者不

Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

+0

它仍然發生沒有@Override – yayestechlab