Two different parameter types (cast Object to Type)

74 views Asked by At

I want to call a method but the parameter could be a Button or an ImageButton. I call the method two times with different parameter types as Objects.

In my method attributesOfButton I want to assign the corresponding button type like 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 it doesn't work. If I for example do this:

currentButton.setEnabled(true);

I get

Cannot resolve method setEnabled(boolean)

1

There are 1 answers

2
JP Moresmau On

Your object currentButton is still defined as Object, so you can't use anything else than Object's methods on it even if you know it's a subclass. You need to have an object defined with the proper 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
    } 
}