A call method that exists in child classes but not in the parent class

public class Parent {
    ....
}

public class Child1 extends Parent {
    ....
    public void foo() {
        ....
    }
}

public class Child2 extends Parent {
    ....
    public void foo() {
        ....
    }
}

Here, the method foo()exists only in Child classes and cannot be added to the Parent class (even an abstract method). In this situation, when I want to call a method foo()on objwhich is a reference Parent, then I need to use intanceofwith a few if..elsethat I want to avoid.

Parent obj = ...// Object of one of the child classes
obj.foo();

EDIT: I need to use the type objonly as Parent. Else I will not call methods on obj, which exists in the parent class.


: , , , , FooInterface foo() , cast obj foo() :

if(obj instanceof FooInterface){
    ((FooInterface)obj).foo();
}

? ?

+4
5

, , , , - , FooInterface foo(), , cast obj foo() :

Parent obj = ...// Object of one of the child classes
.....
if(obj instanceof FooInterface){
    ((FooInterface)obj).foo();
}
+1

, .

FooInterface obj = ...// Object of one of the child classes
obj.foo(); 

foo().

+1

, . .

public class HelloWorld {
    public static void main(String args[]) throws FileNotFoundException {
        SuperClass sc =new Child1();
        if(sc instanceof Child1)//Do same for Child2
        ((Child1)sc).foo();
    }
}

class SuperClass {

}

class Child1 extends SuperClass{
    public void foo(){
        System.out.println("From child1");
    }
}

class Child2 extends SuperClass{
    public void foo(){
        System.out.println("From child2");
    }
}

: child1

0

, except /.

, / - , , .

Here contractmeans abstract methods.


you can try this way where there is no need to test it.

FooInterface sc =new Child1();
sc.foo();

...

interface FooInterface{
    void foo();
}

public class Parent {

}

public class Child1 extends Parent implements FooInterface{

    public void foo() {

    }
}

public class Child2 extends Parent implements FooInterface{

    public void foo() {

    }
}
0
source

You can implement AbstractChildinheritance from Parent, and then extend this class instead Parent:

public class Parent {
    ....
}

public abstract class AbstractChild extends Parent{

    public abstract void foo();

}



public class Child1 extends AbstractChild {
    ....
    public void foo() {
        ....
    }
}

public class Child2 extends AbstractChild {
    ....
    public void foo() {
        ....
    }
}

Therefore, you only need to check if your instance is not instanceof AbstractChild.

0
source

Source: https://habr.com/ru/post/1539411/


All Articles