Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline object instantiation and transformation in Java

Tags:

I have come to Java from Visual Basic, and seem to think I have been, in many ways, spoiled :p

Is there a way to instantiate an object and modify it inline? Something like:

JFrame aFrame = new JFrame();    aFrame.add(new JPanel() {.setSize(100,100) .setLocation(50,50) .setBackground(Color.red) }); 

I was able to @Override methods, but am looking for something simpler. I have search alot, but if there is a specific term for this kind of inline instantiation, it eludes me.

Thank you for your time!

like image 567
GCon Avatar asked Jan 06 '12 21:01

GCon


People also ask

What is instantiation in Java?

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor.

How do you initiate an object in Java?

Creating an Object In Java, the new keyword is used to create new objects. Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor.

How do you instantiate a class in Java?

Java provides the new keyword to instantiate a class. We can also instantiate the above class as follows if we defining a reference variable. We observe that when we use the new keyword followed by the class name, it creates an instance or object of that class.


1 Answers

Yes but some people consider it hacky.

JFrame aFrame = new JFrame(); aFrame.add(new JPanel() {{  setSize(100,100);  setLocation(50,50);  setBackground(Color.red); }}); 

Basically you add another layer of {} (instance initialization block), which is executed when the panel is instantiated. therefore you can put any code in it. (like calling setters).

like image 53
ClickerMonkey Avatar answered Sep 27 '22 22:09

ClickerMonkey