简体   繁体   English

用父类调用子函数

[英]Calling child functions with parent class

I have a java program that simulates a store. 我有一个模拟商店的Java程序。 I have a Product class with 3 child classes (Game, Book, and Movie). 我有一个包含3个子类(游戏,书籍和电影)的Product类。 I have an array of Products, and I want to do something with each item in the array depending on what particular type of child class it is. 我有一个Products数组,并且我想对数组中的每个项目进行某些处理,具体取决于它是哪种特殊的子类类型。

The problem I am having is that the array is an array of Products and, as such, items from it cannot invoke functions of the child classes, even though each "Product" in the array actually is one of the three child classes. 我遇到的问题是,该数组是Products的数组,因此,即使数组中的每个“ Product”实际上是三个子类之一,但数组中的项无法调用子类的函数。

How do I fix this? 我该如何解决? I know I can put a bunch of abstract functions into the Product class that are overridden in the child classes, but I was wondering if there was an easier way of doing this. 我知道我可以在Product类中放入一堆抽象函数,这些抽象函数在子类中被覆盖,但是我想知道是否有更简单的方法可以做到这一点。

If you want to use different functions for each child class you just have to use the "instanceof" operator and type casting like so: 如果要对每个子类使用不同的功能,则只需使用“ instanceof”运算符并像下面这样键入类型:

For example somewhere in a loop: 例如,在循环中的某处:

if(items[i] instanceof Game) {
   Game g = (Game)items[i];
   g.SomeGameSpecificFunc();
} else if(items[i] instanceof Book) {
   //...
}

You can also get a string with a name of the class of current object through reflection, but this is rather slow: 您还可以通过反射获得一个带有当前对象类名称的字符串,但这很慢:

String className = items[i].getClass().toString();

//in Java 7+
switch(className) {
   case "Book":
      //do something
      break;
      //etc
}

But you should use these techniques only if you really really have to use functions with different names and parameters. 但是,只有在确实必须使用具有不同名称和参数的函数时,才应使用这些技术。

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

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