I have an interface BaseModel
public interface BaseModel
{
String toString();
}
and an abstract class BaseData
public abstract class BaseData
{
public abstract String toString();
}
I want my model classes to override the toString() method. For this I tried the following ways, one at a time, but not together:
-
Make all my model classes implement the
interface BaseModel -
Make all my model classes implement the
abstract class BaseData
In the first case I do not get a compilation error if I do not override the toString() method in my model class. I guess it it considering the Object.toString() method as a valid implementation.
But in my second case, if I do not override the toString() method, I get a compilation error:
The type
Titlemust implement the inherited abstract method
BaseData.toString()
where Title is one of my model class that extends BaseData but does not override toString().
Why is the discrepancy?
Thanks in advance.
When you call the toString from your interface, JVM will search for a toString method in your
Titleclass and all its extended classess. eg. Keep searching till it reaches the end of the tree = Object class.In java you can only extend 1 class. So your abstract class extends Object.class and overrides the toString method.
Sincs
Titleextends your abstract class, it cannot extend the Object.class by itself.