我可以在我的超类中使用子类的名称吗?

use*_*550 1 java subclass superclass

我有超类,看起来像:

 public abstract class Fish {

 protected int size;

 protected float weight;

 //constructor

 public Fish(int s, float w) {
 size = aSize;weight = aWeight;}
Run Code Online (Sandbox Code Playgroud)

我有这个超类的2个子类.第一:

 public class SomeFish extends Fish{

 //constructor

 public SomeFish(int s, float w) {

 super(s, w) }
Run Code Online (Sandbox Code Playgroud)

第二个:

public class AnotherFish extends Fish{

 //constructor

 public AnotherFish(int s, float w) {

 super(s, w) }
Run Code Online (Sandbox Code Playgroud)

我要做的是在Fish类中编写一个String toString方法,返回类似于:12 cm 0.5 这里应该是适当类型的鱼(AnotherFish或SomeFish).我可以不使用字符串toString方法抽象并在SomeFish和AnotherFish类中实现字符串toString方法吗?

Boh*_*ian 5

请参阅this实例的类,它将是实际的类(可能是子类):

public abstract class Fish {

    // rest of class omitted

    @Override
    public String toString() {
        return "A " + size + "cm, " + weight + "kg " + getClass().getSimpleName();
    }
}
Run Code Online (Sandbox Code Playgroud)

该调用getClass().getSimpleName()将返回String "AnotherFish"等.

无需在子类中定义任何内容即可使其工作.