简体   繁体   English

scala-无法覆盖Java类的受保护变量

[英]scala - Cannot override protected variable of java class

I am trying to override a Java class that looks somewhat like this 我试图覆盖看起来像这样的Java类

public class ExampleJava {
  public ExampleJava(String string) {

  }

  protected String string;
}

When I use 当我使用

class ExampleScala(string : String) {
  @Override
  protected override def string : String
}

in Scala, the compiler gives the error: 在Scala中,编译器给出错误:

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) {
  ^

UPDATE: I can't modify ExampleJava as it is in a program being extended and if this was released it would not work 更新:我不能修改ExampleJava,因为它在正在扩展的程序中,如果发布了它,它将无法正常工作

  1. You don't use @Override in Scala; 您不会在Scala中使用@Override only the Java compiler is aware about it. 只有Java编译器知道它。 In Scala override is used instead. 在Scala中,改用了override

  2. protected String string; in ExampleJava is a field, so it can't be overridden at all. ExampleJava中,由于它是一个字段,因此完全不能覆盖它。 If you want it to be overridable, you need to write 如果您希望它是可重写的,则需要编写

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

instead. 代替。 You'll also need an actual implementation in ExampleScala . 您还需要ExampleScala的实际实现。

You cannot @Override field member, you can only override methods, It is just an annotation that makes sure at compile time weather you are really overriding method or not 您不能@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. 如果使用此注释类型对方法进行注释但未覆盖超类方法,则要求编译器生成错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM