Search code examples
javasubclasssuperclass

can i use the name of subclass in my superclass?


I have superclass, that looks like:

 public abstract class Fish {

 protected int size;

 protected float weight;

 //constructor

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

and I have 2 subclasses of this superclass. First one:

 public class SomeFish extends Fish{

 //constructor

 public SomeFish(int s, float w) {

 super(s, w) }

Second one:

public class AnotherFish extends Fish{

 //constructor

 public AnotherFish(int s, float w) {

 super(s, w) }

What I have to do is to write a String toString method in the Fish class, that would return something like: A 12 cm 0.5 here should be proper type of fish (AnotherFish or SomeFish). Can I do it without making string toString method abstract and implement string toString method in both SomeFish and AnotherFish classes?


Solution

  • Refer to the class of the this instance, which will be the actual class (possibly a subclass):

    public abstract class Fish {
    
        // rest of class omitted
    
        @Override
        public String toString() {
            return "A " + size + "cm, " + weight + "kg " + getClass().getSimpleName();
        }
    }
    

    The call getClass().getSimpleName() will return the String "AnotherFish" etc.

    No need to define anything in a subclass to make this work.