new instance of the class in java main method - java

I am new to java, I was wondering why I need to create a new instance of the class to use its non-static methods in the main method but not in the other methods like the following
public class Test {
public void test(){
System.out.println("test");
}
public static void main(String args[]){
test(); // error Cannot make a static reference to the non-static method test() from the type Test
}
public void tst(){
test(); // no errors
}
}

Look, main is static method. You call it from the class which hasn't been initialized yet. You can do that, however you can't call Test#test without having an instance of Test.
Working code:
public class Test {
public void test(){
System.out.println("test");
}
public static void main(String args[]){
Test test = new Test();
test.test();
}
public void tst(){
test(); // no errors
}
}
Explanation:
Non-static methods must be called on objects. Objects are created with new keyword. Sometimes, there are methods which return new objects, but they call new inside.
Static methods can be called without creating an object. You then need to declare them static. How? Simply add static before return type.
Example of how static methods work:
public class Test {
public void test(){
System.out.println("test");
}
public static void main(String args[]){
tst();
Test test = new Test();
test.test();
}
public static void tst(){
Test test = new Test();
test.test();
}
}
There were no errors in tst() because you called the method which you saw from that scope. It means that if there was an object of class Test created, you could call tst and test. If you tried to call tst before my refactor, you would have been warned the same warning.

By definition
Static methods, belong to the class, meaning you can use them by calling
ClassName.methodName();
Instance methods (non-static) must be called on instances of an object of a certain class.
like
Test test = new Test();
test.test();

You can't call a non-static method from static area for this any how you have to create an object and through this object only you can call this method.
Or if you want to call directly the method from static area then make method also static.
Why?? Normally in java there are 3 types of variable based on our declare position 1) local variable 2) Instance variable and 3) static variable, same as instance method and static method also.
NOTE Static method or block execute at the time of class loading and that time you are trying to call a normal method and the scope of normal method is same as the scope of object so, without creating object u can't think also about a normal/instance method.

Think of static methods as existing outside of any instance of that class. It is really an instance-less method. In order to call non-static methods, you must reference an instance in order to invoke it.
Another way to look at the issue is from the point of view of the variables. Static variables are shared by all instances of the class and do not belong to a single instance.
public class Test {
private static int var1 = 0;
private int var2 = 0;
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
var1++;
test1.testMethod();
test2.testMethod();
System.out.println("var1=" + var1);
System.out.println("test1.var2=" + test1.var2);
System.out.println("test2.var2=" + test2.var2);
}
private void testMethod() {
var1++;
var2++;
}
}
will produce the following
var1=3
test1.var2=1
test2.var2=1
Static methods are also shared by all instances of a class so do not have direct access to non-static variables.

In java a class has fields and methods (or functions). Keyword 'static' can be added to both of these entities.
Entities marked with keyword 'static' are class related and other entities are instance related. For accessing static fields or methods of a class we require only the class and its instance (created by using new keyword) is not required to be created.
Methods and fields which are not marked static belong to an active instance of the class.
Now suppose there is a class Test.java and we have no instance of it. We can call any of its method which is marked as static. Try thinking an answer to : "From inside an static method (without an instance of the class) how can we call a method or how can we access a field which belongs to some instance?"
For acessing non static field or method from an static method we need an instance. If the 'calling method' is non static then it must have been invoked on an object. If now we call another method from this non static 'calling method' we can eaisly do that as that method will be invoked on the same object as on which the 'calling method' has been invoked upon.
As mentioned by Xavi in his answer you can also refer to
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html for understanding about 'static'.
All non static methods and fields have 'this' (https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html) associated with them, which refers to the current active instance of the class.
Hence 'main' method being static can not call any non static method without instance of the class 'Test'

That's lesson 1: create an object from your class:
Test test = new Test ();
test.test(); // will print test

public static void main is a static method, meaning it's not being executed in the context of a particular instance of the class.
Any method not qualified with static needs to be invoked in the context of a specific instance of the class, that's why it's necessary to instance an object or dispose an instance of the class to invoke if from a static context, or to call it from a non-static context such as your public void tst() method.
I'd strongly recommend going through some basic Java tutorials such as Understanding Class Members.

To call static method, you only need the class, while "non-static" we need a instance of the particular class(create an object of the class).

Related

non-static variable CAN be accessed by static main method through calling class object .how? [duplicate]

I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone

Couple of questions on java method calling

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.

How is the Static method(main) able to grab hold of non static method(constructor) and execute it?

Seems like a very basic query but I was pondering how the static method main() below is able to execute a non static method(the constructor obviously) from it using the new keyword. Though I understand that new brings onto the table a few other things as well but how should I convince myself that this isn't an exception to the rule that static and non static methods can't using non static and static context respectively?
Below is the sample code:
public class ConstructorTest {
ConstructorTest(String str)
{
System.out.println("Constructor Printing "+str);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConstructorTest cnst=new ConstructorTest("here");
}
}
The above code actually prints --> Constructor Printing here
or in other words executing the body of a Non static method from a Static method?
Any plausible explanations are welcome.
The Java Tutorial states that
[...] Constructors are not members.
Therefore, there is no problem in calling them, since they are not bound to instances of your class. This would not make sense - hence, you cannot do the following:
Thing thing = new Thing();
Thing anotherThing = thing.Thing();
A constructor is not a method, so you cannot apply "method logic" to them.
In case you want to know more, the whole instantiation process is very well documented in the JLS. See 12.5. Creation of New Class Instances.
Actually constructor is compiled into the static method, this is how JVM internally creates instances of classes.
You are executing non-static code, but you are not doing it in a static context.
for instance:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
do();
}
}
This can not work, since do is an instance method, which might run code that is specific to the instance. So, how would the VM know which instance to use, or what value x should have?
Now, to first use a constructor, which is possible from any context:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
C1 t = new C1();
t.do();
}
}
Here, even though you are calling the method from within a static method, you are using it through an instance, so not in a static context.
ConstructorTest is not a method.
its an constructor,and you can use the constructor for initialize class property.
you can also initialize the static variable from the constructor like that :-
public class XYZ
{
static int i=0;
public XYZ() {
i=1;//not an compile time error
}
public static void doSome(){}
public static void main(String[] args) {
}
}
On a formal language level you should read the line
ConstructorTest cnst = new ConstructorTest("here")
as a class instance creation expression. As a matter of fact, this is not a call to a constructor or any other method.
The instance creation does many steps, like allocating memory for the new object, initializing the fields, calling constructors and initializer blocks. See JLS §12.5 for a detailed step-by-step description. Thus being said, the constructor invocation is only a part of the instance creation.
Additionally, you might see constructors as being static parts of the class. In fact, constructor declaration are not members (see JLS §8.8) and thus they are not overridable (as static methods also). Beware: This is only half true. When being inside the constructor you already have the instance created, and you are able to call other instance methods and/or access instance fields.

regarding static method in java

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.

Static method in java

I heard that static methods should use only static variables in java.
But, main method is also static, right?
Your question: is the statement " static methods should use only static variables" correct?
No. The statement is not correct.
The correct statement will be "static methods can only use those instance variables that are defined static"
Take a look at following code and read the comments:
Class A{
int i;
static int j;
public static void methodA(){
i = 5; //cannot use since i is not static
j = 2; //can use.
int k = 3; //k is local variable and can be used no problem
**EDIT:**//if you want to access i
A a = new A();
//A.i = 5; //can use.
a.i = 5; // it should be non-capital "a" right?
}
}
First of all, a technicality: it's NOT true that "main method is also static". You can define a non-static main method, with whatever signature you choose; it just won't be a valid Java application entry point.
With regards to "static methods should use only static variables", this is also NOT true. The key concept here is that static methods and fields are class-specific, not instance-specific. You simply can't access an instance variable/method if you don't actually have an instance of that class; it's a compilation error.
So to be precise, without an instance, you can't access instance fields/methods. You can access static fields/methods without an instance. If you need to access instance fields/methods from a static method, you have to get an instance of that class one way or another, either by simply instantiating it, or by getting a reference to it from a static field or method parameter.
Let's take a look at this simple example:
public static void main(String args[]) {
System.out.println(args.length);
}
length is NOT a static field; it's an instance field of array instances, which args is. The static method main is able to get this instance (and thus access its instance methods and fields) because it's passed in as an argument.
Also, println is NOT a static method; it's an instance method of PrintStream instances. The static method main is able to get this instance by accessing the static field out of the class System.
To summarize:
A Java application entry point is a method that:
is named main
is public and static
returns void and takes a String[] argument as parameter
A method named main doesn't have to be a Java application entry point
(but it's best to reserve this name for that purpose)
Furthermore,
Instance fields/methods can only be accessed through an instance
Static fields/methods can be accessed without an instance
Static methods can get an instance of a class by one of the following ways:
creating a new instance
having it passed as an argument
accessing it through a static field of a class
accepting it as the return value of a static method of a class
catching it as a thrown Throwable
Maybe this piece of code will enlighten you:
public class Main {
private String instanceField = "Joe";
private void instanceMethod() {
System.out.println("Instance name=" + instanceField);
}
public static void main(String[] args) {
// cannot change instance field without an instance
instanceField = "Indy"; // compilation error
// cannot call an instance method without an instance
instanceMethod(); // compilation error
// create an instance
Main instance = new Main();
// change instance field
instance.instanceField = "Sydney";
// call instance method
instance.instanceMethod();
}
}
So you cannot access instance members without an instance. Within the context of a static method you don't have a reference to an instance unless you receive or create one.
Hope this helps.
To access non-static fields (instance variables) you need to have an instance.
Inside a non-static method, this is used as default instance:
class AnyClass {
private String nonStaticField = "Non static";
void nonStaticMethod() {
this.nonStaticField = "a text"; // accessing field of this
nonStaticField = "a text"; // same as before
}
}
Inside a static method there is no this to use as default instance, but you can1 still access instance variables if you provide the instance:
class AnyClass {
private String nonStaticField = "Non static";
static void staticMethod() {
AnyClass example = new AnyClass();
example.nonStaticField = "new value for non-static field";
}
}
1 - the field must also be accessible by Java's access control (declared public or in the same class ...)
A static method is called on a class instance and not to an object of a class. This means, that a static method is not able to access instance variables, because they are only instantiated in an object.
If you want to access an instance variable with a static method, you have to declare that variable as static.
public class Test {
private static int value = 0;
public static void main(String[] args) {
value++;
}
}
But to be honest, it's not the best idea to write everything in static methods. It's better to use the main method to instantiate new objects.
One important thing is that unless u create an instance of an class the instance variables don't exist practically it means JVM doesn't that there os an variable like int i unless u create an instance for that class. so, using an instance variable in a static method is an compilation error.
class A{
int i;
static int j;
static int b(){
i=10; // cannot be found
A a= new A();
a.i=10;//can be found in a's instance
}
}
But, we can use instance variables in instance methods because, instance methods are only called when object created so there is no problem in using instance variables inside it.
Hope ur clear about these things!
Yes static method cannot call non-static methods or variables of the class directly.
EDIT : One can create any local variables.
The static method can't access non-static variables outsides because you can use static method without class initialization, but it doesn't work for non-static outside variable. But you can define and use non-static variable in the static method.

Categories