Search code examples
javaandroidclasssubclass

Problem of Returning the main class instead of the subclass JAVA android


I have a function and I would like it to return one of the subclasses which inherit from the same class. The master class is button and the inheriting classes are button1, button2 ... I do not understand when my function returns something it is always the characteristics of the master class that stand out.

My final goal is to pass the variable of a button class in function of a role user. In the example bellow there are just the name.

Here it's how I declare the class Button1, Button2 and the main class button.

...
    public static Button1 Button1;
    public static Button2 Button2;


    SettingsAdapter() {
        Button1 = new Button1();
        Button2 = new Button2();
    }

        public static class Button {
             final public static String name = "test";
        ...
        }

        /*** line 1 ***/

        public static class Button1 extends Button {
            final public static String name = "name 1";
            ...    
        }

        public static class Button2 extends Button {
            final public static String name = "name 2";
            ...
        }

Here it's the function

public static SettingsAdapter.Button getButtonPos(int a) {
        if (a == 1) {
            return Button1;
        } else {
            return Button2;
}

If we printf(getButtonPos(1).name)

The output is always test.

The output I want is name 1

How I can make this function really return the class of Button1 or Button2 ?


Solution

  • My guess is, that the static key-word is the problem. Try to remove it.

    A static variable is the same for all instances of this class, so every instance of a sublclass from button has a variable called name with value "test".

    Then button_1 has another variable called name with value "name 1". I think java just takes the first one.

    Also classe names are written in CamelCase, please refactor them. Static variables are in fact accessible with ClassName.VariableName

    If it's not working without static, then use methods. In Button make a method:

    public String getName(){
        return "test"
    }
    

    and just override this method in the subclasses:

    @Override
    public String getName(){
        return "name 1"
    }
    

    At the print the value of getName().

    printf(getButtonPos(1).getName())
    

    Another way is to retreive the class directly

    button1.getClass()
    

    or

    button1.getClass().getName()
    

    when a string is needed.