简体   繁体   English

JAVA:如何在Object的子类中调用方法?

[英]JAVA: How to call a method in a child class of an Object?

i'm trying to solve this problem but really i don't understand the syntax. 我正在尝试解决此问题,但实际上我不理解语法。 Consider the following code: 考虑以下代码:

class Parent {
   private String productCode1;      // Format X9999
   private String productCode2;

    public Parent(String productCode1, String productCode2)
    {
        this.productCode1= productCode1;
        this.productCode2= productCode2;

    } 

}

then i have a child class wich contain the method i want to call 然后我有一个子类,其中包含我要调用的方法

public Child extends Parent{
    private String[] serialNumbers;

    public Child(String productCode1, String productCode2, String... args){
        super(productCode1,  productCode2,);
        int i = 0;

        for(String serialN: args){
            serialNumbers = new String[10]; 
            serialNumbers[i]= serialN;
            i++;
        }

        public String[] getSerialNumbers(){     //This is the method i want to call
            return this.serialNumbers;
        }
}

this is the inventory class 这是库存类

public class Inventory{

public ArrayList<Parent> products;

public Inventory(){

    products = new ArrayList<Parent>();  //Some hard coded items
    products.add(new Parent("A0001", "abcdefg"));
    products.add(new Parent("B0010", "abcdefg"));
    products.add(new Parent("C0100", "abcdefg"));
    products.add(new Child("D1000",  "abcdefg", "firstSN", "secondSN", "thirdSN"));
}

public static ProductLine getProduct(ArrayList<Parent> products, String productCode){

    for(int i = 0; i < products.size(); i++){
         ProductLine product = products.get(i);
         if(product.getProductCode().equals(productCode)){
             return product;  
         }
    }

    return null;

}

Now in the main class i need to perform a check if the object is a Parent-Object or a Child-Object for do that i'm trying to get a serial number, if i get one it means is a child otherwise is a parent. 现在在主类中,我需要执行检查对象是父对象还是子对象的操作,以尝试获取序列号,如果我得到一个序列号,则意味着是孩子,否则是父母。

The only problem i'm trying to use the getserialNumbers() which is in the child class 我正在尝试使用子类中的getserialNumbers()的唯一问题

public Application{
    String inputProductCode = keyboard.nextLine(); //Input product code from user
    Inventory inventory = new Inventory();

    ProductLine pFound = inventory.getProduct(inventory.products, inputProductCode);  //check if is Child item

    String[] serNumb = pFound.getSerialNumbers(); //Here is where i get Error cannot find symbol/method getSerialNumbers
    if(serNumb[0] == null){
          // code continue... 
}

i tried to cast like: 我试图投像:

String[] serNumb = ((ItemisedProductLine)pFound).getSerialNumbers();

It compiles but he trows(as expected) me an "Parent cannot be cast to child" at runtime. 它可以编译,但是他在运行时向我抛出(如预期的那样)“无法将父对象强制转换为子对象”。

I hope i explained well sorry for the long question... 我希望我对这个长期的问题深表歉意...

Right. 对。 You can't do the cast because Parent simply isn't a Child . 您不能做演员,因为Parent根本不是Child

You could use instanceof to check what type of object you have and then only do the cast and the call if you have an instance of Child but you generally want to avoid doing stuff like that. 您可以使用instanceof来检查您拥有的对象类型,然后仅在具有Child实例的情况下才执行强制转换和调用,但通常希望避免执行此类操作。 It's not good OOP. OOP不好。

One thing you could do is put the getSerialNumbers() method in Parent and have always return an empty array and then override it in Child to actually return the Child 's serial numbers. 您可以做的一件事是将getSerialNumbers()方法放在Parent ,并始终返回一个空数组,然后在Child对其进行覆盖以实际返回Child的序列号。

Of course, it may also be worth reconsidering the whole class hierarchy here. 当然,这里值得重新考虑整个类的层次结构。 Does it make any sense for all classes which inherit from Parent to have serial numbers? 对于从Parent继承的所有类都具有序列号是否有意义? If so, you should consider moving all the serial number handling up to Parent . 如果是这样,则应考虑将所有序列号处理移至Parent Will there ever be more subclasses of Parent than Child ? Parent子类别会比Child吗? If not, perhaps Child should just be eliminated. 如果没有,也许应该只是消除Child

This is simple issue in OOP programming model: 这是OOP编程模型中的简单问题:

  • Any Child instance is a Parent instance also. 任何Child实例也都是Parent实例。
  • Any Parent instance may be a Child instance also. 任何Parent实例也可以是Child实例。

If you change Inventory class constructor as following, your program work fine: 如果按以下方式更改Inventory类构造函数,则程序可以正常工作:

public Inventory()
{
    products = new ArrayList<Parent>();  //Some hard coded items
    products.add(new Child("A0001", "abcdefg"));
    products.add(new Child("B0010", "abcdefg"));
    products.add(new Child("C0100", "abcdefg"));
    products.add(new Child("D1000",  "abcdefg", "firstSN", "secondSN", "thirdSN"));
}

or better way is check by instanceof keyword before casting a Parent instance to Child . 更好的方法是在将Parent实例强制转换为Child之前,通过instanceof关键字进行检查。

why Parent class has no getSerialNumbers method? 为什么Parent类没有getSerialNumbers方法? I think you have 2 options: implement in Parent class or does no consider Parents in your logic (test with instanceof). 我认为您有两个选择:在Parent类中实现,或者在您的逻辑中不考虑Parents(用instanceof测试)。

You can not call method of the child class unless and untill it is the abstract method defined in the parent class. 除非并且直到它是父类中定义的抽象方法,否则您不能调用子类的方法。 Because JVM do not understand the methods which is having in the child class. 因为JVM不了解子类中具有的方法。 For that you can do the below thing in the Inventory class. 为此,您可以在Inventory类中执行以下操作。

public class Inventory{

public ArrayList<Parent> products;

public Inventory(){

    products = new ArrayList<Parent>();  //Some hard coded items
    products.add(new Child("A0001", "abcdefg"));
    products.add(new Child("B0010", "abcdefg"));
    products.add(new Child("C0100", "abcdefg"));
    products.add(new Child("D1000",  "abcdefg", "firstSN", "secondSN", "thirdSN"));
}

public static ProductLine getProduct(ArrayList<Parent> products, String productCode){

    for(int i = 0; i < products.size(); i++){
         ProductLine product = products.get(i);
         if(product.getProductCode().equals(productCode)){
             return product;  
         }
    }

    return null;

}

If your goal is to decide whether your object is of type Parent or Child, you can do it with the instanceof keyword: 如果您的目标是确定对象是父类型还是子类型,则可以使用instanceof关键字来实现:

if(pFound instanceof Child) {
     //...
}

If you want to distinguish between the types using a serial number, the Parent class has to implatement the getSerialNumber method as well. 如果要使用序列号区分类型,则Parent类也必须强制使用getSerialNumber方法。

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

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