在子类中强制实现toString() [英] Force toString() implementation in subclasses

查看:105
本文介绍了在子类中强制实现toString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象父类,我希望它能够强制所有子类实现toString()方法。



然而, :

  public abstract String toString(); 

导致编译错误:

方法'java.lang.String toString()'的类的重复方法名称/签名... 

我相信这可能是由于groovy已经定义了toString造成的。

谢谢

toString()是 java.lang.Object 类,它已经有了一个默认的实现。所以你基本上不能强迫子类来实现它。如果你想强制这种行为(不知道为什么),那么你可以做下面的事情:

  public class abstract SuperClass 
{
public abstract String myToString();

public String toString()
{
//打印超类文件

//启用子类执行打印
myToString( );
}
}


I have an abstract parent class, and I would like it to force all subclasses to implement toString() method.

However putting:

public abstract String toString();

is causing a compilation error:

Repetitive method name/signature for method 'java.lang.String toString()' in class ...

I believe this might be caused by groovy already having toString defined.

Thanks

解决方案

The toString() is part of the java.lang.Object class which already has a default implementation for it. So you essentially can't force the sub-classes to implement it. If you want to force this kind of behavior (not sure why) then you can do something like below

public class abstract SuperClass
{
  public abstract String myToString();

  public String toString()
  {
  //print super class fileds

  //enable subclass to do the printing
  myToString();
  }
}

这篇关于在子类中强制实现toString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆