how to access non static method in static method code example
Example 1: can non static method access static variable
Yes, a non-static method can access a static
variable or call a static method in Java.
There is no problem with that because of
static members . both static variable and
static methods belongs to a class and can be
called from anywhere, depending upon
their visibility. For example, if a
static variable is private then it can
only be accessed from the class itself,
but you can access a public static variable
from anywhere by calling with classname.
Example 2: static vs non static java
public class MyClass {
private static int myInt;
static {
myInt = 1;
}
public static int getInt() {
return myInt;
}
}
System.out.println(MyClass.getInt());
public class MyClass {
private int myInt;
public MyClass() {
myInt = 1;
}
public int getInt() {
return this.myInt;
}
}
MyClass myObj = new MyClass();
System.out.println(myObj.getInt());