Java 是否可以在限制泛型类型的同时扩展泛型类?

Java 是否可以在限制泛型类型的同时扩展泛型类?,java,generics,Java,Generics,假设我有抽象类或接口 public abstract class Animal public abstract class Bird Extends Animal 和泛型类 public class Lifestyle<A extends Animal> 我能想到的唯一的选择是相当糟糕的: public class BirdLifestyle<B extends Bird> { private Lifestyle<B> lifestyle // te

假设我有抽象类或接口

public abstract class Animal

public abstract class Bird Extends Animal
和泛型类

public class Lifestyle<A extends Animal>
我能想到的唯一的选择是相当糟糕的:

public class BirdLifestyle<B extends Bird>
{
  private Lifestyle<B> lifestyle // tells the bird how to do animal things.

  public Lifestyle<B> getLifestyle()
  {
    return lifestyle;
  }

  // Bird-specific methods.
}
我的朋友都比较专业,所以他们都写过这样的东西:

public class LionLifestyle implements LifestyleInterface

虽然我会写:

public class Lifestyle<A extends Animal> implements LifestyleInterface

这似乎是不必要的代码编写量,而且许多代码是以相当机械的方式编写的,这违反了一些编程规则。例如,如果我想向Lifestyle接口接口添加任何方法,那么我需要记住在BirdLifestyle类中添加一个新的单行方法。有没有更干净的方法

我现在几乎被你的问题迷住了。但您可以将您的BirdLifestyle类更改为:

public class BirdLifestyle extends Lifestyle<Bird> { }

再说一次,为什么要将类设置为泛型?BirdLifeStyle这个名字应该真正描述一只鸟的生活方式。你有不同种类的鸟吗?

我现在对你的问题几乎不知所措。但您可以将您的BirdLifestyle类更改为:

public class BirdLifestyle extends Lifestyle<Bird> { }

再说一次,为什么要将类设置为泛型?BirdLifeStyle这个名字应该真正描述一只鸟的生活方式。你有不同种类的鸟吗?

我不太清楚你到底在问什么,但你的第一次尝试似乎可以通过以下方式轻松解决:

public class BirdLifestyle<B extends Bird> extends Lifestyle<B> {
    // ...
}

将起作用。

我有点不清楚你到底在问什么,但你的第一次尝试似乎可以通过以下方式轻松解决:

public class BirdLifestyle<B extends Bird> extends Lifestyle<B> {
    // ...
}

会有用的。

我想这会有用的:公共类鸟类生活方式扩展了生活方式。你在问题中混淆了太多东西,让人很难理解。此外,无论你在哪里说它不起作用,你都不知道你会犯什么错误。在让BirdLifestyle实现AvianLifestyleInterface接口时,您遇到了什么问题?我认为这会奏效:公共类BirdLifestyle扩展了生活方式。您在问题中混淆了太多东西,这让人很难理解。此外,无论你在哪里说它不起作用,你都不知道你会犯什么错误。在让BirdLifestyle实现AvianLifestyleInterface时,您遇到了哪些问题?非常感谢。对不起,是的,有不同种类的鸟;我会尝试更新问题,让它更清楚。非常感谢。对不起,是的,有不同种类的鸟;我将尝试更新问题,使其更清楚。谢谢-我不知道你可以这样做,但这很有意义。谢谢-我不知道你可以这样做,但这很有意义。
public class BirdLifestyle<B extends Bird>
{
  private Lifestyle<B> lifestyle;

  public Lifestyle<B> getLifestyle()
  {
    return lifestyle;
  }

  // 'AvianLifestyleInterface' methods.

  @Override
  public void fly()
  {
    // Code for flying.
  }

  // etc.

  // 'LifestyleInterface' methods.

  @Override
  public void walk()
  {
    getLifestyle().walk();
  }

  // etc., creating a similar one-line method for each method in 
  // 'LifestyleInterface' that is just an entry-point to the same 
  // method in the 'Lifestyle<A>' object.
}
public class BirdLifestyle extends Lifestyle<Bird> { }
public class BirdLifestyle implements AvianLifestyleInterface { }
public class BirdLifestyle<B extends Bird> extends Lifestyle<B> {
    // ...
}
public class BirdLifestyle<B extends Bird> extends Lifestyle<B> implements AvianLifestyleInterface {
   // ...
}