开发者

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

开发者 https://www.devze.com 2022-12-07 22:31 出处:网络
I\'ve got a main class and two inherited class: public class mother{ public String Melement; } and public class boy extends mother {

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 and 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 both object, but it doesn't work

This is what i tried:

public void mymethod (moth开发者_开发技巧er MyObject) {

if (MyObject instance of boy) {

String A = MyObject.Melement;
String B = MyObject.Belement;

}

if (MyObject instance of girl) {

String A = MyObject.Melement;
String B = MyObject.Gelement;

}

}

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

Is it possible to do it? How?


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;

0

精彩评论

暂无评论...
验证码 换一张
取 消