在toString()中使用继承/扩展的具体类名

时间:2014-02-22 02:44:55

标签: java class oop tostring

大家好,我的toString()看起来像这样:

public String toString () 
    {
        return ("A " + size + "cm " + weight +  "kg Fish" );
    }

打印出类似这样的东西:“16厘米0.2公斤的鱼”

我正在寻找它打印出这样的东西:“一个16厘米0.2千克的低音”,其中Bass从NonEndangeredFish类继承其属性,其中它的属性来自Fish类。 to String目前位于Fish类中。这是Fish类:

public abstract class Fish 
{
    // Any fish below this size must be thrown back into the lake
    public static int  THROW_BACK_SIZE = 18; 
    public static float WEIGHT_LIMIT = 10;

    protected float weight;
    protected int  size;


    public Fish(int aSize, float aWeight) 
    {
        size = aSize;
        weight = aWeight;
    }


    public boolean isDesirableTo(Fisher f) 
    {
        if(canKeep() && f.numFishCaught < f.LIMIT && this.weight + f.sumOfWeight < WEIGHT_LIMIT)
        {
          return true;
        }
        else
        {
        return false;
        }
    }

    public abstract boolean canKeep(); 

    public int getSize() { return size; }
    public float getWeight() { return weight; }

    public String toString () 
    {
        return ("A " + size + "cm " + weight +  "kg" );
    }

这是超类。 EndangeredFish类和NonEndangeredFish类扩展了Fish类(它们都是抽象的)。然后Perch类和Bass类扩展NonEndangeredFish类和AtlanticWhiteFish类,AuroraTrout类扩展Endangered类。我的问题是如何在toString()中使用类名?我尝试在Perch,AuroraTrout,AtlanticWhiteFish和Bass中声明一个名为name的字符串并在toString中使用它并且它不起作用,然后我尝试在fish类中声明一个名称(String)然后使用三个参数创建一个构造函数但那没有用,所以我真的卡住了。这就是添加鱼的方式:

public class FishingTestProgram2 
{

    public static void main(String [] args) 
    {
        // Create a big lake with 15 fish
        Lake   weirdLake = new Lake(15);
        weirdLake.add(new AuroraTrout(76, 6.1f));
        weirdLake.add(new Perch(32, 0.4f));
        weirdLake.add(new Bass(20, 0.9f));
        weirdLake.add(new Perch(30, 0.4f));
        weirdLake.add(new AtlanticWhiteFish(140, 7.4f));
        weirdLake.add(new Bass(15, 0.3f));
        weirdLake.add(new Bass(90, 5.9f));
        weirdLake.add(new Bass(120, 6.8f));
        weirdLake.add(new AtlanticWhiteFish(80, 4.8f));
        weirdLake.add(new AuroraTrout(42, 3.2f));
        weirdLake.add(new Bass(100, 5.6f));
        weirdLake.add(new Bass(45, 2.0f));
        weirdLake.add(new Perch(16, 0.2f));
        weirdLake.add(new Bass(30, 1.2f));
        weirdLake.add(new Perch(7, 0.1f));

感谢任何帮助谢谢!

2 个答案:

答案 0 :(得分:3)

这样做:

public String toString () 
{
    return ("A " + size + "cm " + weight +  " " + this.getClass().getSimpleName() );
}

答案 1 :(得分:0)

我怀疑他们应该在每个具体课程中覆盖toString()(我说它更好):

class Bass {

   ...
   public String toString() {
      return super.toString() + " Bass"; 
   }

   ...

}