Home > database >  Convert Reference to Parent to Reference to Child
Convert Reference to Parent to Reference to Child

Time:05-13

I have an ArrayList of an object type, let's call it 'Parent'. I need to use a method (.method1()) that is only available in its child, another object called 'Child'. I'm 100% certain every reference to an instance of 'Parent' that I'm trying to convert is also an instance of Child. Is there any way to convert the reference? (New to java)

A representation of what I'm trying to do:

Child Extends Parent{...}


public void randomMethod(ArrayList<Parent> a){
    for(Child c: a){
        c.method1() //method1 is a method of Child but not parent using attributes Parents do not have
    }
}

note: Please don't tell me to change my pre-existing code, I'm working with a skeleton code.

CodePudding user response:

This will only work if List<Parent> is also a List<Child>. If that is the case then you have to cast each Parent instance to Child.

public void randomMethod(ArrayList<Parent> a){
    for(Parent p: a){
        ((Child)p).method1() //method1 is a method of Child but not parent using attributes Parents do not have
    }
}

If the Parent instances are not superTypes of the Child class, then the above will throw a class cast exception.

Here is an example.

class Parent {
}
    
class Child extends Parent {
    String msg;
    
    public Child(String msg) {
        this.msg = msg;
    }
    
    public String childMethod() {
        return msg;
    }
}
    
List<Parent> list =
        List.of(new Child("I am the first child"),
                new Child("I am the second child"));
    
for (Parent p : list) {
    String s = ((Child) p).childMethod();
    System.out.println(s);
}

prints

I am the first child
I am the second child
  • Related