My Inner and outer class file here:-
package com.demo;
public class Outer {
int outer_x=100;
void test(){
Inner inner =new Inner();
inner.display();
}
public class Inner {
void display(){
Outer ob=new Outer();
ob.test();
System.out.println("display: outer_x= "+outer_x);
}
}
}
Another main class acess outer class member :-
package com.demo;
class InnerClassDemo{
public static void main(String args[]){
Outer outer=new Outer();
outer.test();
}
}
Exception:-
Exception in thread "main" java.lang.StackOverflowError
at com.demo.Outer.<init>(Outer.java:3)
at com.demo.Outer$Inner.display(Outer.java:12)
at com.demo.Outer.test(Outer.java:8)
How can resolve this issue ,pls give me any idea?
Your test method creates an Inner and calls its display() method, which creates an Outer and calls its test method. Nothing in your code stops this from continuing forever, until enough methods have been called to fill up the stack space and a StackOverflowError occurs.
Either don't have test call display, or don't have display call test.
I resolved this issue from #rgettman answer modified my Inner and outer class here
package com.demo;
public class Outer {
int outer_x=100;
void test(){
Inner inner =new Inner();
inner.display();
}
public class Inner {
void display(){
System.out.println("display: outer_x= "+outer_x);
}
}
}
Outer.test calls Inner.display which calls Outer.test which calls Inner.display which calls Outer.test which calls Inner.display which...
This goes on until your program runs out of stack space.
You get StackOverFlowError, because your call has a infinite method call which always exceeds program stack.
Your test method calls display and display method calls testunconditionaly.
It is the basic requirement to define a base case for recursive methods, so you should define a base case which will return and stop recursive method calls.
See also
Recursion
Related
I have two classes Parent and Child
public class Parent {
public Parent() {
System.out.println("Parent Constructor");
}
static {
System.out.println("Parent static block");
}
{
System.out.println("Parent initialisation block");
}
}
public class Child extends Parent {
{
System.out.println("Child initialisation block");
}
static {
System.out.println("Child static block");
}
public Child() {
System.out.println("Child Constructor");
}
public static void main(String[] args) {
new Child();
}
}
The output of the above code will be
Parent static block
Child static block
Parent initialization block
Parent Constructor
Child initialization block
Child Constructor
Why does Java execute the code in that order? What are the rules that determine the execution order?
I learn visually, so here's a visual representation of order, as a SSCCE:
public class Example {
static {
step(1);
}
public static int step_2 = step(2);
public int step_8 = step(8);
public Example(int unused) {
super();
step(10);
}
{
step(9);
}
// Just for demonstration purposes:
public static int step(int step) {
System.out.println("Step " + step);
return step;
}
}
public class ExampleSubclass extends Example {
{
step(11);
}
public static int step_3 = step(3);
public int step_12 = step(12);
static {
step(4);
}
public ExampleSubclass(int unused) {
super(step(7));
step(13);
}
public static void main(String[] args) {
step(5);
new ExampleSubclass(step(6));
step(14);
}
}
This prints:
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Step 11
Step 12
Step 13
Step 14
Keep in mind that the order of the static parts matters; look back at the difference between the order of Example's static stuff and ExampleSubclass's.
Also note that the instance initialization block is always executed immediately after the super() call in the constructor (even if that call is implied/omitted), no matter the order. However, order does matter between an initialization block and a field initializer.
There are several rules in play
static blocks are always run before the object is created, so that's why you see print messages from both parents and child static blocks
now, when you are calling constructor of the subclass (child), then this constructor implicitly calls super(); before executing it's own constructor. Initialization block comes into play even before the constructor call, so that's why it is called first. So now your parent is created and the program can continue creating child class which will undergo the same process.
Explanations:
Static block of parent is executed first because it is loaded first and static blocks are called when the class is loaded.
First - run child class only (comment the extend clause) to see the simple flow.
second - go to Static block vs. initializer block in Java? & read the accepted answer over there.
Edit:
Execution happens in SIC way - Static, (non static) Initializer & Constructor.
(Non static) Initializer are copied into every constructor - At the TOP! (hence lines 3/4/5/6)
Before a class is initialized, its direct superclass must be initialized - http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4 (hence parent static block appears first).
Static init blocks are executed at the time of class loading.
In the class hierarchy the order for execution of static init blocks will start from top level class.
In a class the order for the execution of static block is from top to bottom.
Above rule apply regardless of where the static block is present within the class.
(In your code the parent static blocks will be executed first and then the child class static blocks.)
Instance init blocks will be executed after the call to the super(); in the constructor.
Always super(); is the very first statement in a default constructor.
In your code when you create a Child object:
The default constructor of the Child class get executed.
It will call to the super(); constructor.
Then the super class constructor is executed.
The Parent class will execute its super(); call.
After that the instance init blocks in the Parent class are executed.(From top to bottom).
Then the code within the constructor is executed (if any).
Then it will return to the Child class and execute the Child class instance init blocks.
Finally the code in the child constructor get executed (If exists).
Static block in java is executed before main method. If we declare a Static block in java class it is executed when class loads. This is initialize with the static variables. It is mostly used in JDBC. Static block in java is executed every time when a class loads. This is also known as Static initialization block. Static block in java initializes when class load into memory , it means when JVM read the byte code. Initialization can be anything; it can be variable initialization or anything else which should be shared by all objects of that class. Static block is a normal block of code enclosed in braces { } and is preceded by static keyword.
so static block executed first.
Instance Initialization Blocks: Runs every time when the instance of the class is created.
so next Initialization block executed when instance of the class is created.
then Constructor executed
Just wanted to share my findings.
I read in one of the answers on another thread that static blocks are executed first before static fields which is not correct. It depends on which comes first, static field or static block. Have a look at below code. It will try to put things in perspective.
JVM looks for a class which has public static void main(String args[]) so that it can load that class.
It then initialises static fields of this class(if they come before static blocks). These fields can call static methods of this class or another. If they call static method of this class then that method gets served. If they call static method of another class, then static fields or blocks of that class(depending on which comes first) gets initialised first, then this method call is served.
Then, it moves to static blocks.
It comes back to main method.
class TestLab {
static int method(String a) {
System.out.println("in static method of TestLab" + " Coming from " + a);
System.out.println("b is " + b);
return 6;
}
static int a = method("Line 11");
static int b = 7;
TestLab() {
System.out.println("Inside test lab constructor");
}
static {
System.out.println("In static block of TestLab");
}
}
public class Test1 {
public static void main(String[] args) {
System.out.println("inside main method of Test 1");
int a = TestLab.method("Line 26");
}
// static Test ref=new Test();
Test1() {
System.out.println("Default Constructor of Test1");
}
{
System.out.println("In instance block of Test1");
}
static int d = TestLab.method("Line 37");
static int e = methodOfTest1();
static {
System.out.println("In Static Block of Test1");
}
static int methodOfTest1() {
System.out.println("inside static method:mehtodOfTest1()");
return 3;
}
}
Here is the output:
in static method of TestLab Coming from Line 11
b is 0
In static block of TestLab
in static method of TestLab Coming from Line 37
b is 7
inside static method:mehtodOfTest1()
In Static Block of Test1
inside main method of Test 1
in static method of TestLab Coming from Line 26
b is 7
It would be very helpful to ckeck out the object construction process with a step by step debuger, having a view in which you can see how your object is goning through the phases. I found this very useful for clearing the perspective from a higher point of view. Eclipse can help you with this with it's debugger step into function.
Here is what I found while preparing for a certification.
While we run a class, first static blocks/ static variable initialisation happens. If multiple static blocks are there, it will execute it in the order in which it appears,
Then it will execute init blocks/ instance variable initialisation.If multiple init blocks/ variable initialisation are there, it will execute it in the order in which it appears,
Afterwards it will look into the constructor.
Static block gets executed when a class is loaded into JVM. While init block gets copied into the Constructor whose object will be created and runs before creation of object.
control flow is-
static block -> Initialization block -> and finally Constructor.
static block -> This static block will be get executed only once when the control come to the class.(JVM Load this class)
Initialization block -> This Initialization block will be get executed whenever a new object Created for the Class (It will be executed from second statement of the Constructor then following constructor statements- remember First statement of the Constructor will be Super()/this())
Constructor -> This will be get whenever a new object is created.
Static init block executes at the time of class loading only ones.
Init block executes every time before creating object of the class.
Learn more with this video: Java Tutorial by Rajan Jain : Static Init Block and Init Block in java Video14 - YouTube
1: I have a program like..
public class Test{
void dispose(){
System.out.println("disposing");
}
Test t=new Test();
public static void main(String[] args){
t.dispose();
}
}
why cant I call dispose method from main()? if its static and non static relation, why the below code works?
public class Test{
void dispose(){
System.out.println("disposing");
}
public static void main(String[] args){
Test t=new Test();
t.dispose();
}
}
2: should always the method call code shold be in method? because, the below code is not working..
public class Test{
void dispose(){
System.out.println("disposing");
}
Test t=new Test();
t.dispose();
public static void main(String[] args){
}
}
Please clarify me..
Example 1
You are in a static method (main) and trying to access a non-static variable t. You have declared the variable t as:
Test t=new Test();
This has created it as a member variable of the class. Instead you need to declare it as:
static Test t=new Test();
Now the static method can access it (although this is generally not a good way to do things).
Example 2
You are now declaring the variable t as a local variable inside the main method so it is valid to access it from within main.
Example 3
With the exception of initalizer blocks (which you don't need to worry about) all code must go inside a method.
I guess you come from a background in Procedural language like C.
Java is different. It's object-orriented.
Coming to your Question . . . .
Ans1: It's correct to say that you don’t necessarily have to create an instance of a class to use the methods of the class. If a method is declared with the static keyword, the method can be called without first creating an instance of the class. That’s because static methods are called from classes, not from objects.
BUT, you can not call non-static method from a static context (here as in static method main()). WHY?
Because you can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.
However even that's not the exact case over here
You may feel that you have created an instance of the class at line 5 of your code but to to the compiler, it doesn't exists. It's outside the main() method, which is the first thing looked for in any run-able Java program. The compiler then ropes in other parts as required. You can't have executable code that is not in a method, look at your object initialization. In second block of code, the compiler sees the object initialization, so program executes.
Ans2: YES. As mentioned before, You can't have executable code that is not in a method
Illustration:
class DeclarationTest
{
int a = 5;
int b = 10;
int c = a + b;//it is Ok, this is a declaration statement for c
/*
int c;
c = a + b; ------> this is not Ok, you are performing an action here this must be inside a method!
*/
}
If that was the case it would make having methods a bit less useful. . . Think about it.
why cant I call dispose method from main()? if its static and non static relation, why the below code works?
Since you have a instance of Test, so you can use that even in static context.
should always the method call code shold be in method?
Yes. exactly. Either in methods, static block or in constructor. Other places not allowed.
Before starting everything let me clear what is an Class variable and an Object Variable
Class Variable : Static variable, which can be accessed without initializing the Class
Object Variable: non static Variable which can only be accessed on CLass instantiation
So in your case, when the main Gets Called, the Class is not initiated, so the object doesnt get initialized, so you cannot call the dispose method.
The reason the second block doesn't work is because of the static relation.
If a method is not static, then it must have an instance to be accessed. That is why, creating an instance of the class allows you to call the method.
If you made the dispose method static, then you could directly call the method since there is only a single instance of it.
Here is a link to a different question that explains it well:
calling non-static method in static method in Java
Hope this helps :)
why cant I call dispose method from main()? if its static and non
static relation, why the below code works?
non-static variable t cannot be referenced from a static context(compiler exception).
You should always remember that the jvm searches for the main() method and executes it. Methods and blocks are initialized after that.
note:- You always compile and run the class which contains the main method.
You are declaring the variable t as a local variable inside the main method so it is valid to access it from within main.
should always the method call code should be in method?
Yes method calls always need to be inside of a method or in the constructor or initialization block, even static block .
When a java program is being executed JVM looks for main method. Within the main if you don't write anything nothing will happen.
public class Test{
void dispose(){
System.out.println("disposing");
}
Test t=new Test(); //That's ok.
t.dispose(); //causes compilation error
public static void main(String[] args){
//Executed as soon as you run your program.
}
}
You want to call dispose(). What do you want? Call dispose() on object of test as t.dispose() or you can call it using Test.dispose();
Method 1:
public class Test{
void dispose(){
System.out.println("disposing");
}
public static void main(String[] args){
Test t=new Test(); //You need a reference to Test object
t.dispose(); //to call its methods
}
}
Is dispose() in Test static? No... So, you must call it by using Test object.
If dispose() in Test static? then...
Method 2:
public class Test{
static void dispose(){
System.out.println("disposing");
}
public static void main(String[] args){
Test.dispose(); // Since dispose() is static.
}
}
You can't call non static methods by using Class Reference. You must use Class object But you can call static methods by using class objects (not recommended). You should call it using Class Reference.
Method 3: (Not recommended)
public class Test{
static void dispose(){
System.out.println("disposing");
}
public static void main(String[] args){
Test t = new Test();
t.dispose(); //Static members should be accessed using class name
}
}
Yes, you can not call non-static object or variables inside static block. If you declare object as static then your code will work as follow.
public class Test{
void dispose(){
System.out.println("disposing");
}
static Test t=new Test();
public static void main(String[] args){
t.dispose();
}
}
You can also try something like below:
public class Test{
void dispose(){
System.out.println("disposing");
}
{
dispose();
}
public static void main(String[] args){
Test t=new Test();
}
}
Also, we can declare object outside method in class but we can not call method outside method or block.
When studying the java programming language, I meet the following statement
I am confusing about the statement marked with yellow. Especially, what does instance method mean here? If there is an example to explain this point, then it would be much appreciated.
If I have a method:
public static void print(String line) {
System.out.println(line);
}
... and then remove the static keyword ...
public void print(String line) {
System.out.println(line);
}
... it is now an instance method, can no longer be invoked from the class, and must instead be invoked from an instance (hence the name).
e.g.,
MyClass.print(line);
vs.
new MyClass().print(line);
That's really it.
You can call static methods without needing to intantiate an object:
TestObject.staticMethodCall();
For non-static methods you need to create an instance to call a method on:
new TestObject().nonStaticMethodCall();
Consider following sequence.
Define Class X with static void foo() a static method
Define Class Y which calls X.foo() in its main method
Compile the two classes and (somehow) run it
Change X.foo() to be a instance method by removing the static qualifier
Compile only X, not Y
Run the Y class again and observe the error.
On the other hand, if you had changed the body of X.foo in certain ways without changing its static-ness then there would have been no error. For more, look up "binary compatibility"
First of all, you should understand the difference between the class method and the instance method. An example is shown below.
public Class Example{
public static void main(String[] args) {
Example.method1();//or you can use method1() directly here
Example A = new Example();
A.method2();
}
public static void method1(){
}
public void method2(){
}
}
method1 is the class method which you can take it as the method of the class. You can invoke it without initiating a object by new method. So you can invoke it in such way: Example.method1()
method2 is the instance method which requires you to invoke it by initiating the instance of an object, i.e. Example A = new Example(); A.method2();
Additional:
The error is due to the removal of the static modifier of an class method like method1. Then method1 becomes an instance method like method2 which you have to initiate an instance to call.
I am using a MVC model and am trying to create a thread in the controller. When I am in the inner class run() I need to get the correct model but it is throwing a null pointer.
Here is the code to create the inner class and thread from the outer controller:
Thread thread = new Thread(new runWithThread(OpsSec, AmToChange, AgentID, balance, currency, selected_account_obj));
thread.start();
Inside the runWithThread I try to get the correct Model. AMModel is the Model class and withdraw is a method inside it. getModel is defined in the abstract controller I am extending(implementation inheritance).
((AMModel)getModel()).withdraw(10, "USD");
It works in the outer class but not in the inner class and I am not sure why I am getting the null pointer with the ((AMModel)getModel()). Any help would be appreciated.
Thanks
I realized the error. I had "extends AbstractController" in both the controller outer class and in runWithThread inner class. I am using Rational Arch and it didn't flag anything so I didn't notice the error.
I know this is pretty old, but try AMModel.this.withdraw(10, "USD");. Here's a generic example:
class Outer
{
class Inner
{
public void test()
{
Outer.this.variable = 1;
}
}
public int variable = 0;
private Inner inner;
}
After calling inner.test(), variable would be 1.
I have recently found what appears to me to be a new syntax for statically initializing an ArrayList:
new ArrayList() {{
add("first");
add("second");
}};
My question is, what is really happening there? Is that a shortcut for defining a static block (I thought it would need the static keyword)? Or just a way to define a default constructor? Something else? What version of Java did this become valid?
An explanation plus a link to further reading would be greatly appreciated.
edit:
My test class for showing whether initializer block executes before or after the constructor is below. Results show that initializer blocks execute before the other constructor code:
import org.junit.Test;
public class InitializerBlockTest {
class InitializerTest {
{
System.out.println("Running initalizer block");
}
public InitializerTest() {
System.out.println("Running default constructor");
}
}
class SubClass extends InitializerTest {
{
System.out.println("Running subclass Initializer block");
}
public SubClass() {
System.out.println("Running subclass constructor");
}
}
#Test
public void testIt() {
new SubClass();
}
}
Output:
Running initalizer block
Running default constructor
Running subclass Initializer block
Running subclass constructor
You are creating a new anonymous subclass of ArrayList, with an instance initializer which calls add() twice.
It's the same as:
class MyList extends ArrayList
{
{ // This is an instance initializer; the code is invoked before the constructor.
add("first");
add("second");
}
public MyList() {
super();
// I believe initializers run here, but I have never specifically tested this
}
}
...
List list=new MyList();
Note that, personally, I do not advise it as an idiom, since it will lead to class-file explosion.
It is an initializer block for instance variables.
From Oracle's documentation:
Initializer blocks for instance
variables look just like static
initializer blocks, but without the
static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer
blocks into every constructor.
Therefore, this approach can be used
to share a block of code between
multiple constructors.
See: http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
When you write new ArrayList() { } you are creating an anonymous subclass of ArrayList. The { } as in the innermost brackets in your code denote an initializer block and is actually copied into every constructor.
EDIT: You guys sure answer fast!