Create object and Set data using {{ }} - java

I was able to do some experiment using the Java language and surprisingly I came up using this lines of code {{ }}. More over I've noticed using that code structure, I can use any method of the class without creating an object variable for it.
For example:
class Sample {
public void hello() {
// Do something here.
}
}
class SampleTest {
public void testHello() {
new Sample {{ hello(); }};
}
// PSVM ...
}
The question is what is the concept/term called for the statement of line 8?

The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an "instance initializer", because it is declared within the instance scope of the class -- "static initializers" are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class (specified at http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.6) The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors (but not before superclass constructors).
If you want some examples look here: http://c2.com/cgi/wiki?DoubleBraceInitialization
Sarajog

Related

Cannot access FileChooser methods [duplicate]

When I write the following code in Eclipse:
public class MyClass {
System.currentTimeMillis();
}
I get this compile error:
Syntax error on token "currentTimeMillis", Identifier expected after this token
It works if I change that statement to an assignment statement:
long time = System.currentTimeMillis();
Of course, it doesn't cause errors if placed inside a method body or within blocks inside the class body.
Why is this? Is there some compiler level rule that says that only assignment statements or declarations should be present inside the class body?
The class body can only contain declarations.
Specifically, § 8.1.6 of the JLS defines the class body like this:
A class body may contain declarations of members of the class, that is, fields (§8.3), classes (§8.5), interfaces (§8.5) and methods (§8.4). A class body may also contain instance initializers (§8.6), static initializers (§8.7), and declarations of constructors (§8.8) for the class.
ClassBody:
{ ClassBodyDeclarationsopt }
ClassBodyDeclarations:
ClassBodyDeclaration
ClassBodyDeclarations ClassBodyDeclaration
ClassBodyDeclaration:
ClassMemberDeclaration
InstanceInitializer
StaticInitializer
ConstructorDeclaration
ClassMemberDeclaration:
FieldDeclaration
MethodDeclaration
ClassDeclaration
InterfaceDeclaration
;
As you can see, there are no statements in there anyway, so a class body may not directly contain a statement.
If you think about it, it makes sense: at which point should that code be executed? There is no context to tell you about that, so it makes no sense.
This is illegal. In the class body you can have only: blocks, fields, constructors, methods and classes
Yours is neither. And what would you expect it to do anyway? If you want it to be executed when the class is instantiated, then place it in a block:
{
System.currentTimeMillis();
}
Try this way:
public class MyClass {
static {
System.currentTimeMillis();
}
}
If you call System.currentTimeMillis() inside a static statement it works.
The static block will be called when the class "MyClass" is loaded by the class loader.
Is there some compiler level rule that says that only assignment statements or declarations should be present inside the class body?
In a word: yes. At the class body level you can have instance and static member variable declarations, method declarations, nested classes, object initialization blocks, static initialization blocks, and comments. That's it, by definition.
The "compiler level rules" for a language are called its grammar.
You need to call your code from inside a method, not just on its own like that. E.g.
public class MyClass {
public static void main(String[] args)
{
System.currentTimeMillis();
}
}
The above still won't do anything, but it's legal :-)
You dont get the error with the line
long time = System.currentTimeMillis();
because you are specifying a private variable inside the class (long time) and setting them to a default value (System.currentTimeMillis()) so when you make a new instance of the class MyClass, the variable is being instantiated.
calling only System.currentTimeMillis() just has nosense, because you arent doing nothin' (neither having a context or assigning the value to a private variable)
Is there some compiler level rule that
says that only assignment statements
or declarations should be present
inside the class body?
Yes. More specifically, the syntactic rules of programming languages are usually defined as a formal grammar that specifies how syntactically correct programs are formed. In this case, the Java language specification says:
ClassBody:
{ ClassBodyDeclarationsopt }
ClassBodyDeclarations:
ClassBodyDeclaration
ClassBodyDeclarations ClassBodyDeclaration
ClassBodyDeclaration:
ClassMemberDeclaration
InstanceInitializer
StaticInitializer
ConstructorDeclaration
Since a static method call is not one of ClassMemberDeclaration, InstanceInitializer, StaticInitializer and ConstructorDeclaration, it's not allowed to be present directly inside a class body.
long time = System.currentTimeMillis();
is an instance variable, which gets initalized to the current time when the enclosing Object is created. Valid.
System.currentTimeMillis();
is a statement on its own. Invalid, outwith a constructor, method, static iniatilizer etc.

Commands in anonymous blocks inside a class of any use

If seen this question here:
Instance initializer and *this* keyword
and now I ask myself is something like this:
public class Main {
public static void main(String args[]) {
new Main();
}
{ System.out.println(x); } //Error here
int x=1;
}
of any (even just theoritical) use? I mean this part:
{ System.out.println(x); } //Error here
As far as I can say its anonymous so I'd have no idea how to execute it manually, it doesn't seem to be executed automatically is not part of any function or whatsoever. Sorry if this questions is already answered, but the ones that I found targeted {} to restrict the variable scope but in this case I could not think of a way to get into that scope or make it run.
It's an instance initialization block. Whenever you create an instance of the class, it is executed before the body of the constructor you use.
Therefore the only way to execute it manually is by creating an instance of the class in which this block appears (or a sub-class of that class).

Why can't we call the method of the class using the class's object outside a method?

public class Basics {
Basics b = new Basics();
int instanceVariable = 0;
public void behavior() {
System.out.println("Print Something");
}
b.behavior(); // Why this line, b.behavior doesn't work?
public static void main(String[] args){
Basics b = new Basics(); /* Why are we allowed to create an
* object of same name again within
* the same class */
b.behavior(); // This line works
}
}
In the above class, I am able to create object . But I can't call b.behavior outside any class, but I am able to do that within a method. Why is that so? What is the difference?
public class Basics1 extends Basics{
Basics b = new Basics();
Basics1 b1 = new Basics1();
b = b1.instanceVariable; // I don't see error in this line, but previous line shows //error.
b1.instanceVariable // This line doesn't work
}
Why is b1.instanceVariable not working, instanceVariable is the base class instance variable.
You need to understand that a class is a "type definition", not a code block or sequence of statements.
You cannot just write arbitrary statements in a type definition.
Even so, "b1.instanceVariable" is not a statement. "b1.instanceVariable" doesn't mean anything in statement context.
A class defines variables and methods. b.behavior(); is a statement that cannot be on its own like that.
All code needs to be in methods, in field declarations (such as Basics b = new Basics(); in your example) or in "initializer blocks" (which are run as part of constructors or during class initialization).
This is just a syntax rule.
In other languages, you can have this kind of "raw code", to achieve various effects. What do you want to achieve?
run during compilation (like in Perl): Cannot be done in Java
run during constructor: use an init block
run during class loading: use a static init block
run when the program starts: put it in static void main
run during method invokation: put it in that method
Write code anywhere and expect it to execute is a form of procedural programming. In this form , you tend to loose context and soon the code becomes a spaghetti code --> methods getting called anywhere , anytime.
With OOP, you are trained to create objects with well defined methods which have a defined context. Just think, when would you like to get the b.behavior(); being called : Before initializing a class, after initializing the class, after execution of main or when the object is destroyed?
Interestingly, Java has defined syntaxes for each of the states.. You can wrap your code in { System.out.println("Hello World "); } and it will execute when the class is instantiate...Also you can use static { System.out.println("Hello World "); } and this will execute when class is loaded. But again, this is part of telling the JVM when to do it - an agreed upon syntax.. But without any marker around your code, when would you actually expect to run?

When is it OK to create object of a class inside a method of that class?

public class TestClass(){
public static void main(String []args) {
TestClass t1 = new TestClass();
t1.anything();
}
}
Is it not strange to create a object in the definition of same class? Because then in response - this object creates a new object, then this new object creates another, and the infinite loop begins to never end until the memory is full.
Is it not strange to create an object in the definition of the same class
than in response the object create a new object then this new object
create another and the infinite loop begins
No, the main method only runs once when you run your program. It will not be executed again. So, the object will be created only once.
Think of your main method to be outside your class. Which creates an instance of your class, and uses the instance created. So, when you create an instance from main method, the constructor is invoked to initialize the state of your instance, and then when the constructor returns, the next statement of your main method is executed.
Actually, you can consider main method not to be a part of the state of the instance of your class.
However, had you created the instance of your class inside your constructor (say 0-arg), and the reference as instance reference variable, then that will turn into an infinite recursion.
public class A {
private A obj;
public A() {
obj = new A(); // This will become recursive creation of object.
// Thus resulting in StackOverflow
}
}
You would only have an infinite loop (stack overflow error) if you tried to do the below:
public class TestClass {
public TestClass() {
TestClass t = new TestClass();
}
}
And elsewhere, you try to create an object of the class TestClass.
public class TestClass{
public static void main(String []args) {
TestClass t1 = new TestClass();
t1.anything();
}
}
This is a perfectly valid code. When the main method is called, no prior instance of the TestClass exists (it needs not, because the main method is static).
public class Test2{
public Test2 clone(){
return new Test2();
}
}
This is perfectly valid as well. When you create a new instance of Test2, it contains the clone method, but the method is not automatically executed. Only when the clone method is called, one more instance of Test2 is created.
public class MyLinkedList{
MyLinkedList next;
MyLinkedList(int elems){
if(elems>0){
next = new MyLinkedList(elems-1);
}else{
next = null;
}
}
}
is perfectly valid as well, even if the constructor creates a new instance using the same constructor, because the creation is guarded by a conditional, so creating an instance sometimes triggers a new creation.
public class Fail{
public Fail(){
new Fail();
}
}
Is the only problematic example here. The compiler doesn't complain. It can be translated into byte code and it can be executed. At the runtime, however, you cause a stack overflow:
a new Fail is allocated
its no-arg constructor is called
the constructor tries to create a new Fail
a new Fail is allocated
its no-arg constructor is called
...
The compiler allows this, because, in general, the compiler cannot prevent all infinite recursion. The compiler allows anything that can be translated into bytecode.
The compiler, however, may issue a warning if it detects a method or a method chain calls itself unconditionally.
It's not really odd. All object oriented languages that I am aware of allow this. The code is semantically part of the object definition, but in practice it can be considered separate from the actual state of any given object. So there is no loop because object construction doesn't call your method (unless, of course, it does - then you have a problem).
When you use new to create object constructors are called which initializes the instance variable this happens till all the constructors of your super class have been called .
if you put the some code inside constructor that will run each time you create an object
When a program starts it executes the main method. In java you cannot create a method outside of a class. All methods must be encapsulated within a class. Therefore the main method as an entry point to the program must be within a class. When you run this program the main method will be run once and will execute the code inside it. In your case it creates an object of the enclosing class TestClass. This does not have to happen. It can create objects outside of this class as well. You will only get an infinite loop as explained in the #adarshr's answer.
It's not strange at all. You see, the main() method is the starting point of execution. So figuratively, java is "blind" (doesn't see what you've told it to execute/run) unless it has "seen" the main() method. It's after "seeing" the main() method that it now has the ability to execute other instructions that follow, so as a takeaway, the main() method literally doesn't belong to the object inside it's own class in the first place.
And for the recursion, it will only occur when you do something like what #Rohit Jain stated. Or per your code, you don't invoke anything but you rather invoke the main() itself.
public static void main(String []args) {
TestClass t1 = new TestClass();
main(String[] args);
}
}
The reference variable t1 literally didn't invoke main because it's static. And the nice thing is that, main isn't invoked by your code rather the "jvm", so sensu stricto, you can't remove the static from there. It'll cause some good error message explicitly telling you that the static is supposed to be there. That's why you see main() not invoked by the object in the above snippet.
If you do one these then recursion will occur other than that, you are safe to create an object inside it's own class. Albeit, I wouldn't recommend that. Let one class have the main() method and instantiate (create object) other classes inside that Main class (the class that contain the main method). That way you get to run the code once.

Static Block in Java [duplicate]

This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 8 years ago.
I was looking over some code the other day and I came across:
static {
...
}
Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?
It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).
It can be thought of as a "class constructor".
Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.
It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.
From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
If you have a class with a static look-up map it could look like this
class MyClass {
static Map<Double, String> labels;
static {
labels = new HashMap<Double, String>();
labels.put(5.5, "five and a half");
labels.put(7.1, "seven point 1");
}
//...
}
It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.
It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.
It is also possible to write non-static initializers, which look even stranger:
public class Foo {
{
// This code will be executed before every constructor
// but after the call to super()
}
Foo() {
}
}
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
A static block executes once in the life cycle of any program,
another property of static block is that it executes before the main method.
Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation.
http://www.jusfortechies.com/java/core-java/static-blocks.php
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.

Categories