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).
Related
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?
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
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.
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.
I have a class with several methods and there is no constructor among these methods.
So, I am wondering if it is possible to call a method of a class without a creation of an instance of the class.
For example, I can do something like that:
NameOfClass.doMethod(x1,x2,...,xn)
In general I do not see why it should be impossible. I just call a function which does something (or return some values). If it is possible, what will happen if the method sets a value for a private variable of the class. How can I reach this value? In the same way?
NameOfClass.nameOfVariable
It's called static variables and static methods. Just try it and see that it compiles.
If the methods are static, yes.
But you won't be able to access non-static members.
1) YES, you can use the methods of a class without creating an instance or object of that class through the use of the Keyword "Static".
2) If you declare the method as "Static" then you can call this method by :
*ClassName.MethodName()*
3) E.g.
class Hello {
public static void print()
{
System.out.println("HelloStatic");
}
}
class MainMethod {
public static void main(String args[])
{
// calling static method
Hello.print();
}
}
4) The output of the above program would be : HelloStatic
As many have pointed out: This is only possible if the method is static. Maybe some OOP background is in order: A method should always belong to a class. So what is the use of calling a method without an instance of a class? In a perfect OO world there shouldn't be any reason to do that. A lot of use cases that have to do with static methods talk about assigning some kind of identity to your class. While this is perfectly reasonable in a programming world it isn't very convincing when it comes to object oriented design.
As we program in an imperfect world there is often a use case for a "free function" (The way Java or C++ implement sort() for example). As Java has no direct support for free functions classes with only static "methods" are used to express those semantics with the added benefit of the class wrapper providing a "namespace". What you think of this workaround and if you see it as a flaw in language design is IMO a matter of opinion.
In most languages you can do it only if method is static. And static methods can change only static variables.
I have a class with several methods and there is no constructor among these methods.
If you don't explicitly define a constructor then you get a default constructor provided by the compiler. So if those methods aren't static, try this:
NameOfClass x = new NameOfClass();
x.doMethod(x1,x2,...,xn);
A method on a class operates in the context an instance; it has access to the instance's member variables. You understand this, because you ask about what happens if the method accesses one of those variables.
You can understand why it doesn't work by asking yourself the question: "Where is the data?" If you don't have an instance, where is the instance variable? Where is the data? And the answer is that it doesn't have a place and therefore doesn't work.
The difference with a static function and static member variables is that you can answer the question about the location of the data. The static variables available regardless of whether there is a specific instance or not. The instance specific vs. class specific decision is one that you must make considering what you actually want to do.
That would be static methods.
I have a class with several methods
and there is no constructor among
these methods.
Do you mean you have something like:
public class X
{
public void foo()
{
}
}
or do you mean you have something like:
public class X
{
private X()
{
}
public void foo()
{
}
}
If it is the fist way then, yes, there is a constructor and it will look like this:
public X()
{
super();
}
if it is the second way then there is probably a method like:
public static X createInstance()
{
return (new X());
}
If you really mean can classes have methods that do things without ever creating an instance, then yes you can, just make all of the methods and variables static (usually this is not a good idea, but for some things it is perfect).
Since qre is a static method and doesn't have an access to instances of the enclosing class you'll have first to create an instance and then access it. For example:
public class Foo {
private int bar;
public static void qre() {
Foo foo = new Foo();
foo.bar = 5;
System.out.println("next bar: " + (++5));
}
}
In proper encapsulation, you should not "see" what is happening upon instanciation. To rely on a class's lack of a constructor is breaking this form. The designed of the class my have in mind to add formal state initialization in the constructor at a later date. Your "contract" with the class is only that you can use the methods as they are currently designed.
If you desire to use the functionality of that method without the class overhead, maybe it best for you to include that method in your existing "client" class (of course this is just "copy and paste" coding and is considered an anti-pattern of of software design.
If you are using lombok, here is what you can do:
package util;
import lombok.experimental.UtilityClass;
#UtilityClass
public class UtilFunctions {
public static int SumOfTwoNumber(int a, int b){
return a+b;
}
}
In UtilFunctions class here with #UtilityClass annotation, you can keep all the functions which you want to call anywhere in your project. For the sake of simplicity, I have created a function SumOfTwoNumber which I want to use in my main class. Here is how I can call it in the main class:
import util.UtilFunctions;
public class HeadFirstJavaApplication {
public static void main(String[] args) {
int a = 10, b = 20;
int sum = UtilFunctions.SumOfTwoNumber(a,b);
System.out.println(sum);
}
}
P.S: Don't forget to add lombok dependency to be able to use it. In case of gradle, here is how to add the lombok dependency:
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.16'
annotationProcessor 'org.projectlombok:lombok:1.18.16'
testCompileOnly 'org.projectlombok:lombok:1.18.16'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.16'
}