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.
You cannot create a new variable for a class within the same line that you creating a new object of that class. If you would like to add a new variable to the button class you have to either, modify the class to include your new variable or create a class extension like Jean-François Savard is saying.
Buttondoes not have a fielda, and you want an object that's aButtonand has a fielda, then you must create a new class that extendsButtonand has a fielda.