简体   繁体   English

Java 继承与泛型

[英]Java Inheritance with generics

Can somebody explain (like for dummies) the following examples of inheritance in Java:有人可以解释(比如傻瓜)Java 中的以下继承示例:

1) public class Dog <T extends Animal> {....
2) public class Buldog extends Dog<DogFood, DogCommands> {....
3) public class Buldog<T extends DogFood, K extends DogCommands> extends Animal implements LivingBeign, LivingThing<T,K> { ....
1) public class Dog <T extends Animal> {...

There will be an generic type In your Dog class which is inherit variables and methods from class (probably an abstract class Animal) This T must have and animal property.. For example assume you have a class Mammalian.在你的 Dog 类中会有一个泛型类型,它是从类(可能是一个抽象类 Animal)继承变量和方法,这个 T 必须具有和动物属性。例如假设你有一个类哺乳动物。 We know that all mammalian are animal so they have what all animals have, and they can what all animals can.我们知道所有哺乳动物都是动物,所以它们拥有所有动物所拥有的东西,并且它们可以拥有所有动物所能拥有的东西。

So yo can call this as所以你可以称之为

public Dog<Mammalian> myDog = ...

There is a different situation.还有一种不同的情况。

2) public class Buldog extends Dog<DogFood, DogCommands> {....

So your dog class should be written like所以你的狗类应该写成

/** T refers the food, and K refers commands*/
public class Dog<T,K> {....

So when you want to extend your class with Bulldog, you can leave generic or specify those generic types..所以当你想用 Bulldog 扩展你的类时,你可以保留泛型或指定那些泛型类型。

3) public class Buldog<T extends DogFood, K extends DogCommands> extends Animal implements LivingBeign, LivingThing<T,K> { ....

This is also as easy as above codes.这也和上面的代码一样简单。 The difference that you are desiring subclass of DogFood, which can be anyting, it can be Pap or Milk or Meat, and some subclass of DogCommands for example SitCommand, PlayCommand.. And as you are creating Buldog you know that It is Animal, so you don't want to write animal's property and methods again and since in Java you can't multiple inherit, you want also the other interfaces methods in your class..不同之处在于您需要 DogFood 的子类,它可以是任何东西,可以是 Pap 或 Milk 或 Meat,以及 DogCommands 的一些子类,例如 SitCommand、PlayCommand .. 当您创建 Buldog 时,您知道它是动物,所以你不想再次编写动物的属性和方法,因为在 Java 中你不能多重继承,你还想要你的类中的其他接口方法..

I hope it is more understandable now.我希望现在更容易理解了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM