简体   繁体   中英

Android java method - Can a parameter be more than one type?

I'm new to java/android and would really appreciate help with this. I would like my java method to be able to take in more than one type for the parameter. For example the variable myButton could be an ImageButton or just a Button. The code inside myFunction is valid for whether myButton is an ImageButton or a Button.

if (condition) {
    ImageButton myButton = (ImageButton) findViewById(R.id.myButtonID);
    myFunction(myButton);
} else {
    Button myButton = (Button) findViewById(R.id.myButtonID);
    myFunction(myButton);
}

public void myFunction(Button or ImageButton myButton) {
    ....identical code for myButton which could be an ImageButton or Button....
}

I could obviously write out 2 funcions for parameter type and call it when applicable but that seems like a waste and there must be a quicker way. How can I do this? Thanks for your help.

If both classes have a common interface that can be used inside your method, you can use it and catch both types.

Otherwise, you can use overloading or generic method.

Depends on what the method does to the passed in parameter.

Usually, you'd use polymorphism . Looking at the inheritance graphs,

ImageButton extends ImageView extends View extends Object

and

Button extends TextView extends View extends Object

The most specific common superclass is View . If the method can work on View s, then you should specify the parameter type to be a View :

public void myFunction(View view) {
    //...
}

If the method does different things to ImageButton s and Button s, then you can use method overloading . That is, two methods that have take different parameters:

public void myFunction(ImageButton imageButton) {
    //...
}

public void myFunction(Button button) {
    //...
}

In rare cases, a generics -based solution could also work. Note that the compiler will actually generate copies of the code for each different type passed in, so you should prefer polymorphism-based solution when you can:

public <ParamType extends View> void myFunction(ParamType param) {
    //...
}

You should use common super class of the Button and ImageButton which is for example View and then:

public void myFunction(View view) {
    if(view instanceof Button) {
        Button btn = (Button) view;
        // do something with Button instance
    }

    if(view instanceof ImageButton) {
        ImageButton iBtn = (ImageButton) view;
        // do something with Image Button instance
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM