Accessing non-static members through the main method in Java - java

As a rule in object-oriented paradigm, a static method can have access only to static variables and static methods. If it is so, an obvious question arises as to how can the main() method in Java has access to non-static members (variables or methods) even though it is specifically public static void...!!!

The main method does not have access to non-static members either.
public class Snippet
{
private String instanceVariable;
private static String staticVariable;
public String instanceMethod()
{
return "instance";
}
public static String staticMethod()
{
return "static";
}
public static void main(String[] args)
{
System.out.println(staticVariable); // ok
System.out.println(Snippet.staticMethod()); // ok
System.out.println(new Snippet().instanceMethod()); // ok
System.out.println(new Snippet().instanceVariable); // ok
System.out.println(Snippet.instanceMethod()); // wrong
System.out.println(instanceVariable); // wrong
}
}

By creating an object of that class.
public class Test {
int x;
public static void main(String[] args) {
Test t = new Test();
t.x = 5;
}
}

The main() method cannot have access to the non-static variables and methods, you will get “non-static method cannot be referenced from a static context” when you try to do so.
This is because by default when you call/access a method or variable it is really accessing the this.method() or this.variable. But in the main() method or any other static method(), no "this" objects has yet been created.
In this sense, the static method is not a part of the object instance of the class that contains it. This is the idea behind utility classes.
To call any non-static method or variable in a static context, you need to first construct the object with a constructor or a factory like your would anywhere outside of the class.

YourClass inst = new YourClass();
inst.nonStaticMethod();
inst.nonStaticField = 5;

You have to instantiate the object you wish to access.
For example
public class MyClass{
private String myData = "data";
public String getData(){
return myData;
}
public static void main(String[] args){
MyClass obj = new MyClass();
System.out.println(obj.getData());
}
}

Through the reference to the object.
public class A {
private String field;
public static void main(String... args) {
//System.out.println(field); <-- can not do this
A a = new A();
System.out.println(a.field); //<-- access instance var field that belongs to the instance a
}
}

You must create an instance of the class in order to reference instance variables & methods.

Related

Regarding main method in java

In static method & static block, we can't use the instance variable & we can't create an object then how we use instance variable & create an object inside the main method, because of the main method is also a static method.
Your first assumption is correct while the second is wrong. You can create a new instance inside a static method.
You cant directly access the non static instance variables in a static method. But you can create an object of the class in the static method and access both the static and non static instance variables of the object (which is a local variable inside that static method) in the static method.
public class MyClass {
int i = 78;
public static void main(String args[]) {
MyClass c = new MyClass();
System.out.println("i is = " + c.i);
}
}
You can create object inside main method and call to static method and variable you need
classname.staticMethod().
Inside main write down
classname instance _variable= new classname().
The classes which contains satic method(s) usualy marked with final modifier. A final class is a class that can't be extended.
You can use static methods for Util classes where you do not need to handle stat just receive sone input data, do something with them and return the result. A good example can be the Apache Commons Lang library. You can check the source code of the org.apache.commons.lang3.StringUtils class here.
You can instantiate any java object in a static method, example:
public final class StaticDemo {
public static String echo(String text) {
String response = new String("say ") + text; // for only demonstrating purpose
return response;
}
}
In a static method you can only use static class members:
public final class StaticDemo {
private static final String SAY = "say";
public static String echo(String text) {
String response = SAY + text; // for only demonstrating purpose
return response;
}
}
Class variables hold the state of the object so it does not make any sense to use them from a static method which is belongs to the class.

Yet another non static variable cannot be referenced issue

I've read this, and also this and I guess I'm getting the theroical point af static and non static content but I'm unable to apply it to the following case (which is supposed to work) May be so, so, so basic but... humans.
public class MyClass {
private String varA ;
private int varB;
public MyClass(String var, int var) throws SocketException {
//stuff to work with
}
private void methodA() {
//more stuff....
}
public static void main(String args[]) throws IOException {
//How to instatiate MyClass(varA,varC)?
}
}
So, how it's supposed to be instatiated MyClass from main if MyClass is not static?
How to instatiate MyClass(varA,varC) ?
public static void main(String args[]) throws IOException {
//local variables
String varA = "A";
int varC = 10;
//Use the constructor of the class to create an object
MyClass myClassObj = new MyClass(varA, varC);
}
You always need to use the constructors provided by the class to instantiate a class. You don't have the default (no argument) constructor in your class, so you need to pass the constructor arguments as shown above to instantiate the class.
You can look here.
In your MyClass class instance variables varA, varB are created/maintained for each object(instance) separately.
Just to add, if there are any static variables present in a class, they will be maintained only per class (not for each object).
I hope this answer will be helpful for you to understand why main method is static in non-static class
Why is the Java main method static?
Also, in code :
MyClass myClass = new MyClass(varA, varC);
Create new instance of you class using public constructor with your own parameters list.
Agree with JavaGuy.
Just for your clarity's sake, main method is made static so that it can be called from JVM without instantiation of the class. Hence to access any non static member of the class you need to have an instance of the class as mentioned by above solution by JavaGuy.

why it is possible to get access to private field in static method if you pass object as parameter

For example I've got simple class
class Simple {
private int i = 6;
private static void method(Simple obj) {
System.out.println("Value i: " + obj.i);
}
public void method() {
method(this);
}
public static void main(String[] args) {
new Simple().method();
}
}
Why I can get access to i in static method?
private members can be accessible with in the class. Your static method belongs to the same class. Hence you can access.
Modifier Class Package Subclass World
---------------------------------------------
private **Y** N N N
Update: To avoid the confusion, move the static method to other class and try once.
Don't get confused with static and private/public/[default]. Those are two separate things. A static function can access private non-static field because it is part of the class. And thats whats private does, only restricting access to the class level, without any distinction being made between static or not.
If it's the staticness that's bothering you, obj is a proper "not static" object, which us why it has an accessible non-static field. The method being static is irrelevant.
you are accessing instance of object not directly class variable. when you use direly "i" without reference to object its not allowed.
Private variable visibility is by default in with in class access .
public class Simple {
private int i = 6;
private static void method(Simple obj) {
System.out.println("Value i: " + i); //compile Error ::Cannot make a static reference to the non-static field i
}
public void method() {
method(this);
}
public static void main(String[] args) {
new Simple().method();
}
}

Java - Anonymous class are static or not

I know it depends on the context in which the anonymous class has been written (static or non static method).
but look this part of code:
public class A {
int fieldOfA;
private static class B {
int fieldOfB;
}
public static void main(String[] args) {
B obj = new B() { //this anonymous class is static becuase is in the main method.
private static void testMethod() { //so why here i have an error and i can put just a non-static method
//if my class is static ?
//a class static can have static method, but this class no, why?
}
};
}
}
it's sure that anonymous class are static?
An anonymous class is static if the context is static. e.g. in a static method.
An anonymous class is non static if there is a non static context, whether you need it to be non-static or not. The compiler is not smart enough to make a class static if the non static context is not used.
In this example, two anonymous classes were created. One in a static method has no reference to an outer class and is like a static nested class.
Note: these classes are still called "Inner" and cannot have static members even though they have no reference to an Outer class.
import java.util.Arrays;
public class Main {
Object o = new Object() {
{
Object m = Main.this; // o has a reference to an outer class.
}
};
static Object O = new Object() {
// no reference to Main.this;
// doesn't compile if you use Math.this
};
public void nonStaticMethod() {
Object o = new Object() {
{
Object m = Main.this; // o has a reference to an outer class.
}
};
printFields("Anonymous class in nonStaticMethod", o);
}
public static void staticMethod() {
Object o = new Object() {
// no reference to Main.this;
// doesn't compile if you use Math.this
};
printFields("Anonymous class in staticMethod", o);
}
private static void printFields(String s, Object o) {
System.out.println(s + " has fields " + Arrays.toString(o.getClass().getDeclaredFields()));
}
public static void main(String... ignored) {
printFields("Non static field ", new Main().o);
printFields("static field ", Main.O);
new Main().nonStaticMethod();
Main.staticMethod();
}
}
prints
Non static field has fields [final Main Main$1.this$0]
static field has fields []
Anonymous class in nonStaticMethod has fields [final Main Main$3.this$0]
Anonymous class in staticMethod has fields []
From JLS 15.9.5:
An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).
Section 8.1.3 talks more about inner classes, including when they occur in a static context. But they're never static themselves, and thus can't declare static members (other than constant variables).

What does this single static method do?

I'm unsure what this does, I haven't seen it before and can't find any information about it.
private static String[] names = { "A.ttf" };
private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);
static {
for (String name : names) {
cache.put(name, getFont(name));
}
}
That is not a static method but a static block.
Static blocks are executed first(in same order they are declared) when class gets loaded and usually used for initializing things.
in your case it puts all names in "names" to cache.
refer this or an answer on SO for more info
A block is denoted by {\\some code}. A placed static keyword denotes that it is a static block. static block is known as Static Initializers and non static block is known as Instance Initializers.
None of them can contain return statement.
The non-static block will be called every time you are creating a new instance and it will be called/executed just before the Constructor. The static block will be called/executed only once and it will be the first time your are accessing the class.
Example:
class A {
static{ // static
System.out.println("Static block of Class A");
}
{ // non-static
System.out.println("Non-Static block of a instance of Class A");
}
public A(){
System.out.println("Constructing object of type A");
}
}
public class StaticTest {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
}
}
Output:
static block of Class A
Non-Static block of a instance of Class A
Constructing object of type A
Non-Static block of a instance of Class A
Constructing object of type A

Categories

Resources