English 中文(简体)
我希望能恢复它从中援引的一个子类别。
原标题:I want a function to return an instance of the subclass it s invoked from

我想在一流中确定一种功能,即恢复使用该功能的子级。 这就是说,我是A类,职能艰巨。 然后,我创立了B和C子类,延伸A.,我希望B.plugh返回B和C.plugh,以回去C. 是的,他们可以回去A,但打电话的人要么把它投到正确的亚类,这在使用抽签时是痛苦的,要么宣布接收变量为超型,失去类型安全。

因此,我试图用通用语来做,这样写的是:

class A<T extends A>
{
  private T foo;
  public T getFoo()
  {
    return foo;
  }
}
class B extends A<B>
{
  public void calcFoo()
  {
    foo=... whatever ...
  } 
}
class C extends A<C>
{
   public void calcFoo()
  {
    foo=... whatever ...
  } 
}

这似乎可行,但看起来很粗略。

有一件事,我在<条码>A<Text A>上收到警告。 汇编者说,A是通用的,我应具体说明类型。 我猜测,我想说:<条码>,A<Text A<x>。 但是,我会怎么做呢? 我认为,我可以坐在这个无限的场所。

似乎我们不肯撰写<条码>B延伸A<B>,但这不会引起任何投诉,因此可能只是罚款。

这样做是否正确? 是否有更好的办法?

最佳回答
class A<T extends A<T>> {

或者,我更喜欢:

class A<THIS extends A<THIS>> {

java.lang.Enum。 该款对客户代码作了限定,该编码只是希望<代码>A,但必须写到<代码>A<>>。

请注意,这绝不会破坏LSP,而是GOOD OO。

或者,你只能使用var杂式返回类型。

问题回答

从严格的业务协调办公室的角度来看,这是Very Bad ThingTM。 它违反了Liskov Substitution Principle,如果B &C既是A,又是B.getFoo()和C.getFoo(),在这种情况下,C.C.Poo(O)应回去做同样的事,他们就赢得了 t。 如果打电话者需要知道在使用这种方法时会发生什么,那么你的继承等级就错了。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签