fra pet
fra pet

Reputation: 309

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

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...

Upvotes: 0

Views: 4363

Answers (5)

Sam
Sam

Reputation: 6910

This is simple issue in OOP programming model:

  • Any Child instance is a Parent instance also.
  • Any Parent instance may be a Child instance also.

If you change Inventory class constructor as following, your program work fine:

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.

Upvotes: 1

Steffen Stenersen
Steffen Stenersen

Reputation: 375

If your goal is to decide whether your object is of type Parent or Child, you can do it with the instanceof keyword:

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.

Upvotes: 0

QuantumMechanic
QuantumMechanic

Reputation: 13946

Right. You can't do the cast because Parent simply isn't a 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. It's not good 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.

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? If so, you should consider moving all the serial number handling up to Parent. Will there ever be more subclasses of Parent than Child? If not, perhaps Child should just be eliminated.

Upvotes: 2

Bhavik Ambani
Bhavik Ambani

Reputation: 6657

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. For that you can do the below thing in the Inventory class.

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;

}

Upvotes: 0

Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

why Parent class has no getSerialNumbers method? I think you have 2 options: implement in Parent class or does no consider Parents in your logic (test with instanceof).

Upvotes: 0

Related Questions