Thursday, June 15, 2017

What is the reason behind “non-static method cannot be referenced from a static context”

We have seen this is a very common interview question
"“non-static method cannot be referenced from a static context" but most of us does't have clear understanding about why is that soo.

Lets understand this concept.

1. First what do we understand by static : Static variable/methods means these will be loaded/creates   at the time of creation of class. So we got to know static variable/method will be created in memory when the class is loaded and these static variable and method will hold some default values in it.

2.One more this these static variable and method can be accessed using the class name itself, no need to created the object for that.

Above two points i guess every one knows.

Now whats the pain in “non-static method cannot be referenced from a static context"

lets see when the static method and non static methods are created in memory.

Static methods are created when the class is loaded.
Non static methods are created when object for that class is creates.

So if static method will hold reference of non static , and static methods are created when the class is loaded , and the non static will only be created only when  object of the class is created.
So all the calls associated withing static block are not fulfilled.
As is contains ref to a non static block of code, which only be populated when the object for the class is created.

Which leads to the contradiction and can raise ambiguity.

Hope you got my point. :-)

No comments:

Post a Comment

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...