Two different types of parameters (casting an object into a type)

I want to call a method, but the parameter can be Button or ImageButton. I call the method two times with different types of parameters as with objects.

In my attributesOfButton method, I want to assign the appropriate button type, as in the code below.

private void memCheck()
{
    ImageButton imageButtonCam;
    Button buttonCamCo;

    attributesOfButton(imageButtonCam);
    attributesOfButton(buttonCamCo);
}

private void attributesOfButton(Object button) 
{
    Object currentButton;

    if (button instanceof ImageButton) 
    {
        currentButton = (ImageButton) button;
    } 

    if (button instanceof Button ) 
    {
        currentButton = (Button) button;
    } 

    // do something with button like:
    if (Provider.getValue == 1) {
        currentButton.setEnabled(true);
    }
}

But that will not work. If I, for example, do this:

currentButton.setEnabled(true);

I get

Cannot resolve setEnabled (boolean) method

+4
source share
1 answer

The currentButton is still defined as Object, so you cannot use anything else than Object methods, even if you know its subclass. You must have an object defined using the appropriate class:

private void attributesOfButton(Object button) 
{
    if (button instanceof ImageButton) 
    {
        ImageButton currentButton = (ImageButton) button;
        // do stuff for ImageButton
    } 

    if (button instanceof Button ) 
    {
        Button currentButton = (Button) button;
        // do stuff for Button
    } 
}
+2
source

All Articles