Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure the toString() method is reimplemented in class?

Suppose I have an interface and many classes implementing that interface. I want to enforce the overriding of the default implementation of toString() in each of those classes (that is, if some classes do not override it, that should result in a compilation error).

Is it possible to achieve that? Declaring public abstract String toString();, with or without the @Override annotation, in the interface body, is legal, but does not have any effect.

like image 442
k29 Avatar asked Dec 01 '12 20:12

k29


People also ask

Is toString method overridden?

A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.

In which class the toString () method is present?

Object class is the parent class in Java. It contains the toString method. The toString method is used to return a string representation of an object.

Why should the toString method be overridden for user defined classes?

There will be no information about state or properties of an object. Therefore, it is recommended that every class you write must override toString() method so that you quickly get an overview of an object. You must override toString() method in such a way that it should provide enough information about an object.


1 Answers

Yup, kind of.

protected abstract String internToString();

and then

@Override
public String toString() {
 return internToString(); 
}

in your base class.

like image 95
nullpotent Avatar answered Nov 12 '22 21:11

nullpotent