Force override of toString() from interface?

R

Ryan Stewart

Is it possible to specify in an interface (or some other way) that a
class that implements it must override the toString() method of the
Object class?
 
H

Harald Hein

Ryan Stewart said:
Is it possible to specify in an interface (or some other way) that a
class that implements it must override the toString() method of the
Object class?


public abstract class BaseClass {
// require subclasses to implement toString()
public abstract String toString();
}
 
C

Chris Smith

Ryan said:
Is it possible to specify in an interface (or some other way) that a
class that implements it must override the toString() method of the
Object class?

No.

Interfaces have no business doing that. toString is available and does
what it does, and if it makes sense to override it, the implementor of
the class will do so. The interface exists to ensure that a given set
of operations are available on an object, and toString is always
available.

So, if you want to use the class's toString method, you can do so and it
will obey its specified behavior. If you want it to do something
different, then write a new method and have it return a String, and use
that one instead. Commandeering the toString method is very poor form
and likely to be very annoying to users of your interface, especially if
they elsewhere use toString for it's intended purpose (for example,
logging when they want to know the specific instance of an object if it
matters).

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Roedy Green

Is it possible to specify in an interface (or some other way) that a
class that implements it must override the toString() method of the
Object class?

call it display().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top