static fields in Java [duplicate] - java

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 8 years ago.
I have learned that fields are like global variables which can be accessed by the methods inside the same class. I have done it this way before and never had a problem. I have now a class where I have some fields but the methods cannot access them without having to make them static fields. I get the error "cannot make static reference to non-static..."
I thought static was to access fields on other classes without having to create an object reference to the class. The only difference I have with this code is that I have a single class and my main() method within this class. Does having main() inside this class make a difference?

A static member only exists once for the class itself as opposed to regular class members which are distinct per instance of your class.
Having a main() method does not impact the behavior of your static members, however static methods can only access static members while non-static methods can access both static and non-static class members.

You can't access non static instance inside static method. I think you are trying to access class variable inside main method directly, i.e.
class A
{
int x;
main() method
{
x;//Not accessible here,, create instance of class and access it.like
A a=new A();
a.x;
}
}

Static (methods,variables,classes, etc) belongs to Class not to the particular instance of the class. We define as static when the behaviour or state does not depend on any particular instance of the class. For Example "generate a Random Number " it does not depend on the instance, it always generate a number regardless of instance such behaviour can be defined as static.
Regarding the error, posting you code will helpful to give better solution.
Refer the below link to know more about Static and non-static
http://javarevisited.blogspot.in/2012/02/why-non-static-variable-cannot-be.html

Related

Why can't you call a non-static method from a static method within the same class?(Cannot make a static reference to the non-static field) [duplicate]

This question already has answers here:
What is "static"?
(7 answers)
What does the 'static' keyword do in a class?
(22 answers)
Closed 9 months ago.
In Java we can use
non-static variables inside non-static methods without creating an
instance within the same class.
static variables inside non-static methods without having an issue within the same class.
static variables inside a static a static method without having any issue within the same class.
I just want to know why we can not use a non static variable inside a static method within the same class.
It wouldn't make sense. Static methods are about belonging to the class, rather than individual instances. So, they don't have access to any instance (i.e. you can't use this™ inside them).
Things that aren't static are bound to individual instances.

Why there's no error in this code? j is final and static but still accessible using object of class how? [duplicate]

This question already has an answer here:
How static fields are referenced through objects? [duplicate]
(1 answer)
Closed 2 years ago.
interface TempInterface {
static final int j = 30;
}
class TempClass implements TempInterface {
}
public class Try {
public static void main(String args[]) {
TempClass obj = new TempClass();
System.out.println(obj.j);
}
}
In Java, the static keyword means that the variable can be accessed by every object of a class. Java forces every variable in an interface to be both static and final, so every object of a class that implements it will be able to access that variable, but not change it.
A static variable is nothing more than a fixed memory location shared by all instances of the class (since it belongs to the class itself). This means that all of the instances can access it since they know its location. Note however that it is usually frowned upon if you access a static field from an instance instead of a class reference.
For further information I suggest you read up on Oracle's tutorial regarding class variables. To quote a section:
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
Regarding interfaces, you can think of them as special types of classes, so by implementing an interface you inherit all of its data as well (i.e. static variables).
Static means that you have access without need to create new instance, final means - you can'not change but you may get this.
And I can note what interface variable may be accesed from another package too because it's also implicitly public (as static and final).

Static Variables and Methods in Java [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Difference between Static and final?
(11 answers)
Closed 2 years ago.
I am confused about when to use Static variables/methods and exactly what they do. I know Static means that the variable or method becomes a part of the class and not an instance, but when do we use this? Also, if a variable is static, does that mean it is immutable like a final variable? Basically what is the use of Static?
You will usually use static when your variables are general and are not supposed to be part of each instance separately, take as an example the number pi, if you create a Math class, you will set pi as a static final variable, and also the methods will be declared as static, because you don't want to create a class instance everytime you want to use the power function. If your function doesn't use the properties of the class it will probably be static.
Another use I found useful, when you create a class within another, you should declare the inner class as static, otherwise you will need an instance to create instance of the inner class

this keyword and static [duplicate]

This question already has answers here:
Why keyword 'this' cannot be used in a static method?
(13 answers)
Closed 9 years ago.
I knew that we can not use this keyword in a static method, But I got confused why we can not use this inside static blocks orstatic methods. Even the same case with super(). Could anyone shed light on this?
Thanks
this and super refer to the current instance and the parent instance respectively.
Within any static context, whether it is a static block or a static method, there is no instance to refer to, and therefore the keywords are not permitted.
super() is a call to the parent instance's no-arg constructor, and is only permitted as the first statement in a constructor, which disqualifies it from appearing in any static context.
According to the doc
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called. You can refer to any member of the current object from within
an instance method or a constructor by using this.
But the static methods are related to the Class not to the object. in static methods you dont have any instance.
Static methods and blocks are, by definition, linked to the class and not any instance of this class.
As this refers to the current object instance, it is perfectly normal that you cannot use it in any static initialization block or method.
Because this points to an instance of the class, in the static method/block you don't have an instance.
according to Oracle
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called.
So, in a static class you have NO instance variables-objects created. That's why you cannot use the this keyword
Static blocks can be used to initialize static variables for example.
Static merthods are not working within an instance scope either.
Both are related to only the class and have nothing to do with an instance of that class in any way.
To answer this we should consider what static means - it means that this bit is put in a 'static' place in memory, it exists only once.
So every class has static bits and non-static bits. The static bits exist once and the non-static bits can exist many times (i.e. lots of different instances). The word 'this' can then be thought of as shorthand for 'this version of the non-static bits'.
In a static context we have no version of the non-static bits to refer to (or to be more precise we don't know which version we should refer to!) so we have no this. The same argument can be made for super.

java objects, shared variables

I have a simple question here.
If I declare a variable inside an object which was made [declared] in the main class, like this:
public static int number;
(
usually I declare it like this :
private int number;
)
can it be used in a different object which was also made [declared] in the main class?
btw I do not care about security atm, I just want to make something work, don't care about protection)
Here's a telling quote from Java Language Specification:
JLS 8.3.1.1 static Fields
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized.
A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
[Example program follows...]
In short, a static field is a class variable: it belongs to the class, as opposed to the instances of the class. In a way, you can think of a static field as a variable shared by instances of the class, but it's much more consistent to think of static fields as belonging to the class, just like static method also belongs to the class, etc.
Since they belong to the class, they do not require an instance of said class to access (assuming adequate visibility), and in fact it's considered bad programming practice to access static members through an instance instead of a type expression.
Related questions
Java - static methods best practices
Static methods
calling non-static method in static method in Java
non-static variable cannot be referenced from a static context (java)
When NOT to use the static keyword in Java?
Static variables and methods
If the class holding 'number' is called MyClass
you can refer to it as MyClass.number from any method.
Doing so for a variable is not good design though.
There are really two issues here: public vs. private in the context of inner classes, and static variables.
Part 1:
static means that you don't need an instance of the class to access that variable. Suppose you have some code like:
class MyClass {
public static String message = "Hello, World!";
}
You can access the property this way:
System.out.println(MyClass.message);
If you remove the static keyword, you would instead do:
System.out.println(new MyClass().message);
You are accessing the property in the context of an instance, which is a copy of the class created by the new keyword.
Part 2:
If you define two classes in the same java file, one of them must be an inner class. An inner class can have a static keyword, just like a property. If static, it can be used separately. If not-static, it can only be used in the context of a class instance.
Ex:
class MyClass {
public static class InnerClass {
}
}
Then you can do:
new MyClass.InnerClass();
Without the 'static', you would need:
new MyClass().new InnerClass(); //I think
If an inner class is static, it can only access static properties from the outer class. If the inner class is non-static, it can access any property. An inner class doesn't respect the rules of public, protected, or private. So the following is legal:
class MyClass {
private String message;
private class InnerClass {
public InnerClass() {
System.out.println(message);
}
}
}
If the inner class has keyword static, this would not work, since message is not static.
static variables are shared by all instances of a given class. If it's public, it is visible to everything.
non-static variables belong to only one instance.
Since your main method is static, it can only see static variables. But you should avoid working statically - make an instance of a class, and pass the data around as method/constructor parameters, rather than sharing it via static variables.

Categories

Resources