Regarding main method in java - 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.

Related

Is it possible to access a private static variable and method?

We can access a static property of a class by writing className.propertyName, but if the property (method/variable) is private then is it possible to access that property?
For example,
class A{
static int a = 50;
}
public class HelloWorld{
public static void main(String []args){
System.out.print("A.a = ");
A obj = new A();
System.out.println(A.a);
}
}
This will print A.a = 50
But if I change static int a = 50; to private static int a = 50; then can I access that variable any how?
The private keyword means that it'll only be visible within the class. So in your example it means that you cannot access it like A.a. What you can do though is to create a public method that returns a.
private static int a = 5;
public static int getA () {
return a;
}
You can then statically call this method and retrieve the private static field.
// ...
System.out.println(A.getA());
Usually private static fields are rarely used though.
One more thing I'd like to add is the general use of static here.
As you actually create an instance of the class A the static modifier is redundant.
You cannot access the private in outside class or outside the package .Because private making them only accessible within the declared class.if you want to access the variables in the class means public,default and protected are only accessible .outside the package
means default is not possible only public and protected is possible ,protected also have different package and non sub class means not possible only sub class is possible(need to extend the class).public only accessible for all inside and outside the packages.

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();
}
}

How is a call to static method resolved in java?

If static methods are resolved at compile time how is an object instance able to call a static method?
class StaticCall
{
public static void main(String[] args)
{
String arr[]={"Class StaticCall","calls static method of class MyMainClass"};
MyMainClass h=new MyMainClass();
h.main(arr); //How is an instance able to call a static method?
System.out.println("this is StaticCall main");
}
}
class MyMainClass
{
public static void main(String[] args){
System.out.println(args[0]+" "+ args[1]);
}
}
After running the StaticCall class the output is
Class StaticCall calls static method of class MyMainClass
this is StaticCall main
As static fields and methods belong to the Class object how is an instance able to call a static method?
Also when is the Class object created,Is it on first access to any of it's fields or methods?
How is an instance able to call a static method?
It doesn't. Try this instead
MyMainClass h = null;
h.main(arr);
and you will see that the instance is ignored as this is exactly the same as
MyMainClass.main(arr);
To extend your example ... if you have
class AnotherMainClass extends MyMainClass
{
}
then all the following call the same method.
AnotherMainClass amc = null;
amc.main(args);
((AnotherMainClass) null).main(args);
AnotherMainClass.main(args);
MyMainClass mmc = null;
mmc.main(args);
((MyMainClass) null).main(args);
MyMainClass.main(args);
h.main(arr); //How is an instance able to call a static method?
This is just a shortcut for MyMainClass.main(arr), i.e. the static type of h. The usage is often frowned upon and most IDEs will recommend you use the type instead of instance.
Since this occurs at compile time, h can be null
you can call static method by classname.staticMethod and even instance.staticMethod, instance.staticMethod internally call classname.staticMethod.

Accessing non-static members through the main method in 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.

Categories

Resources