This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
I have a class Person, which have unique id of person (type int) for each Person object. I also have a static method isAlreadyStored(String name), which should check if a person with this name was already created. I can't solve this one by creating a list for all created Person objects, because I get error "non-static variable cannot be referenced from a static context", but I don't have any other idea how to iterate over all Person objects to find one with a given name. How do I approach this?
Apparently for solving your problem you need a list of all created instances for Person class. You should store that in a static variable, and then search on it. Something like this:
final static allPeople List<Person> = new ArrayList<Person>();
Then you could search on that list with something like this:
...
if (allPeople.contains(aPerson)){
...
The error non-static variable cannot be referenced from a static context means that you are trying to access a variable defined without the keyword static from a method defined with the keyword static.
For example
public class Main {
private int x = 3;
public static void main(String[] args) {
// Not possible
System.out.println(x);
}
}
A variable defined without the keyword static is named an instance variable and can be accessed only from an instance method (a method defined without the keyword static).
Related
This question already has answers here:
JAVA cannot make a static reference to non-static field
(4 answers)
Closed 2 years ago.
I am trying to access global variables I am getting an error
public class FinalKeyword {
int x=20;
String n= "Broad";
public static void main(String[] args) {
System.out.println(x);
System.out.println(n);
}
}
Error:
Cannot make a static reference to the non-static field
Non-static member (field, method or block without a static modifier) belongs to instance;
Static member belongs to class.
You can't use a member of instance, if you don't have an instance.
FinalKeyword fk = new FinalKeyword();
int x = fk.x; //this will work, as you're accessing a "x" instance member.
String y = fk.n; //same here.
This question already has answers here:
java non-static method getBalance cannot be referenced from a static context
(4 answers)
Closed 5 years ago.
Compare the way I print the value of the members of this class, in the static method (main) v/s a non-static method (the print method). In the static method, I need to use an object of this class, whereas, in the non-static method, I can refer to the class members directly.
I understand that the scope of static is class-wide, and is not tied to an object. Could someone elaborate a bit further on why I need to use an object in the static method, and it's not needed in a non-static method.
public class TreeDriver {
Tree tree;
TreeNode p;
public TreeDriver() {
tree = new Tree();
p =null;
}
public static void main(String[] args) {
TreeDriver obj = new TreeDriver();
obj.print(obj.tree.root, obj.p);
}
public void print(TreeNode nodeA, TreeNode nodeB)
{
System.out.print(nodeA.val + ", " + nodeB.val);
System.out.print(tree.root.val + ", " + p.val);
}
}
The print method isn't a static method, so it can only be called on an instance of the TreeDriver class (i.e. it can't be called from the class directly, like TreeDriver.print(...))
From your perspective, there's no way around this really, as you're accessing the instance variables p and tree in your method.
I would add that it'd probably make more sense if you split out your driver methods (e.g. main(String[] args) away from your data model (i.e. the instance variables and the print method).
Static methods do not need an object instance to be called.
In your above example, another class could call your main function like so.
TreeDriver.main(args);
Notice that TreeDriver is not an instantiated object. Contrast this with how a different class would need to call print.
TreeDrvier newTreeDrvier = new TreeDriver();
newTreeDriver.print(nodeA, nodeB);
You need an instance of the TreeDriver object. Members are defined for an instance of the class, not for the class itself, unless the member itself is static, which in that case would make it a class variable.
By definition, you don't need an instance to call a static method. There's really nothing more to say about "why" than just "that's the definition of a static method."
A non-static method is associated with a specific instance. As an analogy, if I tell you to start the car, you go start a specific car - you can't just grab the key and turn it in mid-air and expect it to "work."
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 6 years ago.
Class1.java
public List<UMRDTO> getDocumentationList(Session session)
{
List<UMRDTO> documentationList = null;
try
{
Query query = null;
query = session.createQuery(UMRSQLInt.DOCUMENTATION_LIST);
documentationList = query.list();
}
return documentationList;
}
I need to use the documentationList that is returned to a static method in this like but getting error like non static method cannot be refrenced from static context
class2.java
static
{
UMRMetadataSupportDAOImpl d=new UMRMetadataSupportDAOImpl();
listDocuments= d.getDocumentationList(); //error here
for (UMRDocumentationDTO listDoc: listDocuments)
{
if(listDoc.equals(MMTConstantsInt.DOMAIN_NAME))
domainDocumentationMap.put(listDoc.getId().getObjectName(), listDoc.getDocumentationLink());
else
domainComboDocumentationMap.put(listDoc.getId().getObjectName(), listDoc.getDocumentationLink());
}
Static fields and methods are linked to the class. They can be invoked just by the classname and dot operator.
Non static fields and members are linked to an instance of the class. They need an object of the class to be invoked. In the same class there is a special reference which refers to the currently executing object called this.
Class is a blueprint and its instances are the realization of that blueprint. When an object is created then in memory the space is allocated. We invoke non static methods on the object.
Your method getDocumentationList is non static meaning it requires an object of class1 so that it could be invoked on that object. You are calling it using a class name instead you need to create an object and then invoke the method.
Second option is to declare getDocumentationList as static.
This question already has answers here:
Cannot refer to a non-final variable inside an inner class defined in a different method
(20 answers)
Closed 7 years ago.
I know,this question has been asked already and I an advance apology for asking it again but I am not able to figure out the exact reason why this is so?Can someone please help me out with it?
For e.g.-
public class File
{
public static void main(String[] main)
{
File obj=new File();
obj.method();
}
void method()
{
for(int i=0;i<10;i++)
{
class Inner
{
void display()
{
System.out.println("i is : "+i); //Gives error,i needs to be declared final
}
}
Inner cls=new Inner();
cls.display();
}
}
}
My questions are-
Why the variable i needs to be declared final if I want to use it in
display() method of Inner class?
If I want to display i inside the display method in each
iteration,then how may I do so?Because if I declare i to be final
with initial value 0,then I will not be able to iterate over it.
Thanks .....
1)That variable needs to be final or effective final because of security reasons. What if the object using in that modifying the passed object??
2) You have to just move your for loop inside the class. No other way around.
An inner class just want to use the the instance members, just use them, that is the only thing you can do inside inner class. You have no command over that. To achieve that functionality, Java made the rule of final or effective final.
Ok, let see what happens when you made the variable final ?
All the copies of those final variables will be used by the inner class not the actual varibles.
If you not heard of the term effectively final here you go : Difference between final and effectively final
This question already has answers here:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
(11 answers)
Closed 3 years ago.
So in my class declared as "public class pcb", I have the following constructor: public pcb(int p, int a, int b).
In public static void main(String[] args) I try to call the constructor in a for loop where I add a "pcb" into a different position in an array. Here is the for loop where the last line is where I get the error:
for(int i=0; i<numJob; i++){
pI = scan.nextInt();
arr = scan.nextInt();
bst = scan.nextInt();
notHere[i]=new pcb(pI, arr, bst);
}
What am I doing wrong? Is it syntax or is it the structure of my program. I haven't used Java that much and I think that's my main problem.
You haven't given all of the relevant code, but the error indicates that pcb is an inner class of fbMain:
public class fbMain {
//...
public class pcb {
}
//...
}
You can fix this error by making pcb static:
public static class pcb {
}
Or by moving the class to its own file. Or, if pcb cannot be static (because it is associated with an instance of fbMain), you can create a new pcb by passing an instance of fbMain:
notHere[i] = instanceOfFbMain.new pcb(pI, arr, bst);
It is likely the first that you want. Please also note that by convention, Java type names start with an upper-case letter.
Add static to your class declaration like this
public static class pcb...