Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 抽象泛型类解释_Java_Generics_Extends - Fatal编程技术网

Java 抽象泛型类解释

Java 抽象泛型类解释,java,generics,extends,Java,Generics,Extends,我正在查看一些代码并试图理解下面代码的逻辑,但下面的示例对我来说太多了: public abstract class NewPage1<T extends NewPage1> extends SuperPage<T> implements Interface1<T>, Interface2<T>{ ... } 你能给我解释一下刚才发生了什么事吗?也许是这个代码的一些用例?为什么这个泛型类是一种T类型,它扩展了自己,然后又扩展了其他

我正在查看一些代码并试图理解下面代码的逻辑,但下面的示例对我来说太多了:

public abstract class NewPage1<T extends NewPage1> extends SuperPage<T> implements Interface1<T>, Interface2<T>{    
    ...
}

你能给我解释一下刚才发生了什么事吗?也许是这个代码的一些用例?为什么这个泛型类是一种T类型,它扩展了自己,然后又扩展了其他泛型类。。。我就是找不到任何合乎逻辑/实际的解释。如果我能弄明白,我将不胜感激。

没有任何上下文,这很难说,但这似乎是一种模式,当您试图用流畅的操作方法编写层次结构时,为了链接调用而返回相同的对象

我们考虑下面的例子:

  abstract class Animal {
     Animal eat() { /* ... */ return this; }
     Animal poo() { /* ... */ return this; }
  }
  abstract class FootedAnimal extends Animal {
     FootedAnimal walk()  { /*...*/ return this; }
  }
  class Dog extends FootedAnimal {
      Dog bark() { /* ... */ return this; }   
  }
使用此类,可以链接方法:

   new Dog()
   .bark()  // returns Dog
   .walk()  // returns FootedAnimal
   .eat()   // returns Animal
   .poo()   // returns Animal
   .eat();  // returns Animal
但是,由于Animal中方法的返回类型,您不能这样做:

   new Dog()
   .eat()    // returns Animal
   .poo()    // returns Animal
   .bark();  // <- bark() does not exist in Animal !!! 

这个类型变量的声明是错误的,因为它当前使用的是一个原始绑定:它应该是NewPage1。如果您正在查看现有代码,是否有任何其他类使用或扩展了NewPage,以便更好地了解t可以是什么。如果真的有一个名为Interface1或Interface2的接口,那么最好去掉这个代码或依赖项:谢谢,伙计。我想你在所有其他代码的上下文中都明白了这一点。
  abstract class Animal<S extends Animal<S>> {
     S eat() { /* ... */ return (S)this; }
     S poo() { /* ... */ return (S)this; }
  }
  abstract class FootedAnimal<S extends FootedAnimal<S>> extends Animal<S> {
     S walk() { /* ... */ return (S)this; }
  }
  class Dog extends FootedAnimal<Dog> {
      Dog bark() { /* ... */ return this; }   
  }
   new Dog()
   .eat()    // returns S=Dog
   .poo()    // returns S=Dog
   .bark()   // returns Dog
   .walk()   // returns S=Dog
   .eat();   // returns S=Dog