Java Static [duplicate] - java

This question already has answers here:
Closed 14 years ago.
Duplicate: What does the 'static' keyword do in a class?
I've read this post already.
What does the "static" keyword in a method do?
I remember being told that static != clingy...but that is pretty much all I know about this keyword.

Static class variables can be thought of as a global class. No matter how many instances of the class you have, there is just one instance of each static variable.
Static methods don't use any non-static class variables and they can be called directly from outside of the class without having to instantiate the class itself.

Static variables and methods belong to the class and not instance, although you can refer them from an instance reference. Usually, you use the Class name to access them.
If a method is declared as static, you don't need the object's instance in which it is defined to invoke it. Now, you might want to know when could such a situation arise? Consider the main method of java
public static void main(String[] args)
Why is it declared static? It's because in order to start your program this method should begin execution. And, since the program hasn't initialized there is no way you could create an instance of the class in which it is declared. Therefore, you are required to declare the class as public. And, this static method gets called when the class is loaded in memory through
java YourClassName
Besides this, static methods are used to modify static variables. They cannot manipulate non-static instance variables.
Also, be aware, that static holds a different meaning in another language like C.

A static method belongs to the Class it is defined in and not to instances of objects of that Class, as non-static methods do. As a side-effect of not belonging to the instances of a Class, it's a compile error to try and access non-static fields in a static method. There's no "this" for the static methods to get access of the non-static fields from.
The Java Math class is a great example because it's loaded with static methods. You never create an instance of the Math class, you just call methods directly from the class.
Math.abs(3.14);

The value of a static variable within a method is stored between calls to that method
public void method() {
static int callCount = 0;
callCount++;
System.out.println("Calls: " + callCount);
}
method(); // "Calls: 1"
method(); // "Calls: 2"
method(); // "Calls: 3"
Note that this is completely different from a static method. A static method is called upon the class it is defined in instead of an instance of this class.
class MyClass {
public static void staticMethod() { ... }
public void nonStaticMethod();
}
Myclass.staticMethod();
MyClass instance = new MyClass();
instance.nonStaticMethod();

a static method is one that's established for the class. It doesn't need (and doesn't have) a this pointer, and can't access instance data. So you can write something ike
public class Hello {
void instanceHello() {
System,out.println("Hello from the instance.");
}
public static void main(int argc, String[] argv){
// The main method is defined even though there are no instances
System.out.println("Hello from main.");
instanceHello(); // but this is a syntax error;
Hello h = new Hello();
h.instanceHello(); // this isn't though
}
}

Related

Making a static reference to a non-static method from inside the method

I understand the "Cannot make a static reference to the non-static method" error, but I came across with this:
public class MyClass {
public static void main(String[] args) {
MyClass myClassInstance = new MyClass();
while (true) {
myClassInstance.myMethod();
myMethod();//Cannot make a static reference to the non-static method myMethod()
}
}// END main
void myMethod() {
try {
//Stuff
}
} catch (Exception e) {
myMethod();
}
}// END myMethod
}// END MyCLass
I can't just call myMethod() from main but I can do it from inside the method itself (in this case I want to call myMethod() again if an exception happens).
How does this work? is myClassInstance still somehow there because at that point I'm still inside myMethod()?
Would it be better to have static MyClass myClassInstance = new MyClass() at class level and then call myClassInstance.myMethod() every time?
First of all you should know more about static and non-static methods:
A static method belongs to the class
and a non-static method belongs to an
object of a class. That is, a
non-static method can only be called
on an object of a class that it
belongs to. A static method can
however be called both on the class as
well as an object of the class. A
static method can access only static
members. A non-static method can
access both static and non-static
members because at the time when the
static method is called, the class
might not be instantiated (if it is
called on the class itself). In the
other case, a non-static method can
only be called when the class has
already been instantiated. A static
method is shared by all instances of
the class. These are some of the basic
differences. I would also like to
point out an often ignored difference
in this context. Whenever a method is
called in C++/Java/C#, an implicit
argument (the 'this' reference) is
passed along with/without the other
parameters. In case of a static method
call, the 'this' reference is not
passed as static methods belong to a
class and hence do not have the 'this'
reference.
Reference:Static Vs Non-Static methods
How does this work? is myClassInstance still somehow there because at
that point I'm still inside myMethod()?
myMethod is an instance method that belongs to myClassInstance. so when you call myMethod() inside myMethod() it's equivalent to this.myMethod()
Would it be better to have static MyClass myClassInstance = new MyClass() at class level and then call myClassInstance.myMethod() every time?
When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. For more information visit Static Variables : Good or Bad?.

Explain to me the difference in these codes and why I'm having an error: non-static variable cannot be referenced from a static context [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

Serious confusion with Scanner.nextLine [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

How does static inner class can access all the static data members and static member function of outer class?

I observed that static inner class can access all the static data members and member function of outer class. How does java do this?
class StaticClass{
static int x=10;
static void show() {
System.out.println("show");
}
public static void main(String[] args) {
InnerStatic i = new InnerStatic();
i.display();
}
static class InnerStatic {
static void display() {
System.out.println(x);
show();
}
}
}
Static members in Java are allocated on one-per-class basis. Since there is only one per-class item for any static member, Java knows where each one of them is at runtime.
Therefore, the only issue here becomes visibility of the item from the point of view of access control. Here, too, Java has no issues, because Java compiler knows from where each static item can be accessed.
In your example, InnerStatic.display can access StaticClass.show in the same way that StaticClass.main can. In fact, any method in the same package as StaticClass is allowed to do this:
StaticClass.show(); // this will compile from anywhere
The advantage of InnerStatic is that the compiler knows of the "surrounding" class, so when it does not find InnerStatic.show it continues looking, and finds the method in the StaticClass.
A static method can access the static fields and methods of any other class unless access modifiers prevent it.
These are accessed in the same way that methods and fields are accessed in the same class.
In your example, inner/outer has nothing to do with it. Your fields and methods are all either public or package-private (i.e., have no visibility modifier), and would be accessible to any class that is in the same package.

Calling Non-Static Method In Static Method In Java [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
I'm getting an error when I try to call a non-static method in a static class.
Cannot make a static reference to the non-static method methodName() from the type playback
I can't make the method static as this gives me an error too.
This static method cannot hide the instance method from xInterface
Is there any way to get round calling an non-static method in another static method? (The two methods are in seperate packages and seperate classes).
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.
You could create an instance of the class you want to call the method on, e.g.
new Foo().nonStaticMethod();
Firstly create a class Instance and call the non-static method using that instance.
e.g,
class demo {
public static void main(String args[]) {
demo d = new demo();
d.add(10,20); // to call the non-static method
}
public void add(int x ,int y) {
int a = x;
int b = y;
int c = a + b;
System.out.println("addition" + c);
}
}
public class StaticMethod{
public static void main(String []args)throws Exception{
methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
the above code not executed because static method must have that class reference.
public class StaticMethod{
public static void main(String []args)throws Exception{
StaticMethod sm=new StaticMethod();
sm.methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
This will be definitely get executed. Because here we are creating reference which nothing but "sm" by using that reference of that class which is nothing
but (StaticMethod=new Static method()) we are calling method one (sm.methodOne()).
I hope this will be helpful.
You need an instance of the class containing the non static method.
Is like when you try to invoke the non-static method startsWith of class String without an instance:
String.startsWith("Hello");
What you need is to have an instance and then invoke the non-static method:
String greeting = new String("Hello World");
greeting.startsWith("Hello"); // returns true
So you need to create and instance to invoke it.
It sounds like the method really should be static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.
However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")
So as long as the method is present in xInterface, and your class implements xInterface, you won't be able to make the method static.
If you can't change the interface (or don't want to), there are several things you can do:
Make the class a singleton: make the constructor private, and have a static data member in the class to hold the only existing instance. This way you'll be invoking the method on an instance, but at least you won't be creating new instances each time you need to call the method.
Implement 2 methods in your class: an instance method (as defined in xInterface), and a static method. The instance method will consist of a single line that delegates to the static method.
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.
class A
{
void method()
{
}
}
class Demo
{
static void method2()
{
A a=new A();
a.method();
}
/*
void method3()
{
A a=new A();
a.method();
}
*/
public static void main(String args[])
{
A a=new A();
/*an instance of the class is created to access non-static method from a static method */
a.method();
method2();
/*method3();it will show error non-static method can not be accessed from a static method*/
}
}
There are two ways:
Call the non-static method from an instance within the static method. See fabien's answer for an oneliner sample... although I would strongly recommend against it. With his example he creates an instance of the class and only uses it for one method, only to have it dispose of it later. I don't recommend it because it treats an instance like a static function.
Change the static method to a non-static.
You can't get around this restriction directly, no. But there may be some reasonable things you can do in your particular case.
For example, you could just "new up" an instance of your class in the static method, then call the non-static method.
But you might get even better suggestions if you post your class(es) -- or a slimmed-down version of them.
The easiest way to use a non-static method/field within a a static method or vice versa is...
(To work this there must be at least one instance of this class)
This type of situation is very common in android app development eg:- An Activity has at-least one instance.
public class ParentClass{
private static ParentClass mParentInstance = null;
ParentClass(){
mParentInstance = ParentClass.this;
}
void instanceMethod1(){
}
static void staticMethod1(){
mParentInstance.instanceMethod1();
}
public static class InnerClass{
void innerClassMethod1(){
mParentInstance.staticMethod1();
mParentInstance.instanceMethod1();
}
}
}
Note:- This cannot be used as a builder method like this one.....
String.valueOf(100);
I use an interface and create an anonymous instance of it like so:
AppEntryPoint.java
public interface AppEntryPoint
{
public void entryMethod();
}
Main.java
public class Main
{
public static AppEntryPoint entryPoint;
public static void main(String[] args)
{
entryPoint = new AppEntryPoint()
{
//You now have an environment to run your app from
#Override
public void entryMethod()
{
//Do something...
System.out.println("Hello World!");
}
}
entryPoint.entryMethod();
}
public static AppEntryPoint getApplicationEntryPoint()
{
return entryPoint;
}
}
Not as elegant as creating an instance of that class and calling its own method, but accomplishes the same thing, essentially. Just another way to do it.
It is not possible to call non-static method within static method. The logic behind it is we do not create an object to instantiate static method, but we must create an object to instantiate non-static method. So non-static method will not get object for its instantiation inside static method, thus making it incapable for being instantiated.
Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.
You can call a non static method within a static one using:
Classname.class.method()

Categories

Resources