Home > Mobile >  How to use a method with an object which could be extended with different class?
How to use a method with an object which could be extended with different class?

Time:12-08

I've got a main class and two inherited class:

public class mother{
    public String Melement;
}

and

public class boy extends mother {
    public String Belement;
}

and

public class girl extends mother{
    public String Gelement;
}

So I could have an object A like boy A = new boy(); and an object B like girl B = new girl();

And I would like to use a method with these objects, but it doesn't work

This is what I tried:

public void mymethod(mother MyObject) {
    if (MyObject instanceof boy){
        String A = MyObject.Melement;
        String B = MyObject.Belement;
    }

    if (MyObject instanceof girl){
        String A = MyObject.Melement;
        String B = MyObject.Gelement;
    }
}

I understand that it's not working because Myobject is of type mother so I could access only Melement But I would like my method to accept the both type of objects boy and girl

Is it possible to do it? How?

CodePudding user response:

Although it the check of instance of does work, you still need to cast it to a Boy class in order to work. Simply do String B = ( (boy) MyObject ).Belement;

  • Related