简体   繁体   中英

How to @Override an Attribute declared in an Interface implemented in a class

Interface:

package II_1_b;



public interface Bezeichnung {

public String Bezeichnungi = "Hallo";
public abstract void setBezeichnung();
}

class:

package II_1_b;

public class Speerwurf extends SportDaten implements Bezeichnung {

private double weite;

 @Override
   public void setBezeichnung(){    //Here we want to Override the String in 
     Bezeichnungi = "Test";         //the Interface
}



public Speerwurf(String n, double w, String bez) {
    super(n);
    this.weite = w;
    bez = Bezeichnungi;
}

@Override
public void display() {
    System.out.println("Speerwurf von " + this.SportlerName + ":\n"
            + weite + " Meter " + Bezeichnungi);
 }

}

You can see our Code here, I commented the problem area and hope you can help us. Stackoverflow tells me to add more details, so I'm gonna describe what I'm going to have for lunch: I think I will make myself a TK-Pizza, maybe 2. I'm often very hungry.

从接口继承到类的字符串 Bezeichnungi 是最终的,因此不能被覆盖。

As @slaw stated, fields in interfaces cannot be changed and are thus static and final. Additionally, there is no sense of declaring fields in an interface, because it only declares a certain behaviour and not a state. To make things work like you showed here, you need to use an abstract class:

package II_1_b;



public abstract class Bezeichnung {

public protected String Bezeichnungi = "Hallo";
public abstract void setBezeichnung();
} 

Concrete class:

package II_1_b;

public class Speerwurf extends Bezeichnung { //think about how to handle SportDaten!

private double weite;

 @Override
   public void setBezeichnung(){    //Here we want to Override the String in 
     Bezeichnungi = "Test";         //the Interface
}



public Speerwurf(String n, double w, String bez) {
    super(n);
    this.weite = w;
    bez = Bezeichnungi;
}

@Override
public void display() {
    System.out.println("Speerwurf von " + this.SportlerName + ":\n"
            + weite + " Meter " + Bezeichnungi);
 }

}

Since we dont know your concrete use case, we cannot help you except of telling you why it does not work the way it should

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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