Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding new variable without extending class

Tags:

java

class

I have button and I'd like to do something like this:

Button b=new Button(){public int a;};
b.a=5;

How to do this in java?

like image 677
oneat Avatar asked Jun 08 '26 13:06

oneat


2 Answers

There is no way to add variables to a class without extending it. However, the extending class does not need to be named: you could use an anonymous class instead, in a way similar to the snippet from your post.

The trick, however, is to access the variable after you have added it: you could do it by mutating objects referenced from the class, like this:

// Prepare a mutable object for use in your class
final AtomicInteger a = new AtomicInteger(123);
Button b = new Button(){
    public void someMethod() {
        ...
        int n = a.intValue();
        ...
    }
};

When you set things up this way, changes to a's state in your method would become accessible to someMethod() of the anonymous subclass of the Button class.

like image 79
Sergey Kalinichenko Avatar answered Jun 11 '26 02:06

Sergey Kalinichenko


It seems like you want a custom Button object.

Simply create a new Class with extends Button and declare in that class the a variable and any other methods that you want to add.

Something like

public class SomeClass extends Button
{
   public int a;
}

public class SomeOtherClass
{
    public static void main(String args[])
    {
        SomeClass someClass = new SomeClass();
        someClass.a = 5;
    }
}

If really you don't want to extend the class, then it is impossible. Sorry.

Also, your example is actually creating an anonymous class which extends Button.

like image 21
Jean-François Savard Avatar answered Jun 11 '26 02:06

Jean-François Savard