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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With