简体   繁体   中英

toString in subClasses Cannot Override abstract toString , Java

I have this very long exercise and I came a cross a problem in each sub class. The problem says and I have no idea what mistake I've made while writing. If you could check the 4 toString methods I would be much apprecaited .

The code is here: http://paste.org/pastebin/view/39488 I know I should past the code here but it is very long and I'm not able to organize it well.

toString() in Shape cannot override toString() in java.lang.Object; attempting to use incompatible return type

toString() in Square cannot override toString() in java.lang.Object; attempting to use incompatible return type toString() in Square cannot override toString() in java.lang.Object; attempting to use incompatible return type `

toString() in Sphere cannot override toString() in java.lang.Object; attempting to use incompatible return type

toString() in Cube cannot override toString() in java.lang.Object; attempting to use incompatible return type

thanks

You need to change the return type of the function to String and return the text instead of writing it to System.out .

public String toString() {
    return  "(" + super.getX() + ", " +
    super.getY() +") " + "side: " + super.getDimension1();
}

EDIT : If you want to have a method that outputs the object directly to System.out in textual form, you'll need to call it something else than toString() . This is because toString() is a method belonging to java.lang.Object which all Java classes automatically extend.

toString() has to return String not void .

// false
public abstract void toString();

// right
public abstract String toString();    

Note: You should not print (System.out) in the toString() method. You should rather return a String represenation of the object.

toString() is implemented in Object class and every class extends it. This method is in every class and we can't have two method with same signature but different return type. As toString() is already there with return type String , we can't have one more toString() with any other return type.

because you try to override it with a void return type. toString should return a String.

它应该返回一个字符串而不是 void。

public abstract String toString()

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