Aidan Goettsch
Aidan Goettsch

Reputation: 75

scala - Cannot override protected variable of java class

I am trying to override a Java class that looks somewhat like this

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:

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

Upvotes: 0

Views: 643

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170745

  1. You don't use @Override in Scala; only the Java compiler is aware about it. In Scala override is used instead.

  2. protected String string; in ExampleJava is a field, so it can't be overridden at all. 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.

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240898

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

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.

Upvotes: 1

Related Questions