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.
Related
This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 2 years ago.
I have a class Program. Here it has main method.It is static method. I created a simple
getAllSum method to return sum of three values.But, if i remove static keyword then i get error as:
**Cannot make a static reference to the non-static method getALlsum(int, int, int) from the type Program
**
If I am calling a function from static method to non static method then,why it is necessary to become non static method to be static?
Static method I have learned about them is that:
Can be called from class name instead of using object.
Each object shares the same variable.
But,I am getting confuse why cant we call a nonstatic function from static function?What is the reason behind this?
public class Program {
public static void main(String[] args) {
int l=getALlsum(1,2,3);
System.out.println(l);
}
public static int getAllSum(int a,int b,int c) {
return (a+b+c);
}
}
You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class.
You need to make an instance of your class, and call your method
This question already has answers here:
JAVA cannot make a static reference to non-static field
(4 answers)
Closed 4 years ago.
Below code gives the error as - cannot make a static reference to a non-static field. Though non-static members can be accessed from a static method using object of the class. Can you please suggest.
package dataTypes;
public class CharDemo {
CharDemo cd = new CharDemo();;
char defaultCharValue;
static void defaultCharValue() {
System.out.println("Default char value from static instance method is "+cd.defaultCharValue); //--error
}
public static void main(String[] args) {
System.out.println("Default char value is "+cd.defaultCharValue);//error
}
}
You cannot call not-static context into static block directly.
Because static context is associated with class and not-static is associated with object.
All static members gets memory at the time of class loading in method area and all non-static gets memory at the time of object creation i.e in heap area.
Hence, Java does not allow to use non-static context in static context directly you need to access it with the help of object.
Here above cd causes problem as it is non-static and you are trying to access directly in static block.
You have to do something like this :-
public static void main(String[] args) {
CharDemo ch = new CharDemo();
System.out.println("Default char value is "+ch.cd.defaultCharValue);//error
}
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:
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).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How come invoking a (static) method on a null reference doesn’t throw NullPointerException?
Can any one explain why the output of the following program is "Called"
public class Test4{
public static void method(){
System.out.println("Called");
}
public static void main(String[] args){
Test4 t4 = null;
t4.method();
}
}
I know we can call static method with class reference , but here I am calling using null reference . please clarify my doubt
In the Byte code
Test4 t4 = null;
t4.method();
will be
Test4 t4 = null;
Test4.method();
Compiler would convert the call with the class name for static methods. refer to this question on SO which i myself have asked it.
It doesn't matter if the instance is null, because you are calling a static method.
Think of it this way.
Every static method is equivalent with a class method whereas a non-static method is equivalent with
an instance method.
Therefor it doesn't matter what value the instance takes as long as you are working with static methods or members.
Static methods can be called via the classname or an instance.
I would try to avoid to call them by an instance (also a lot of tools warn you to do so because of bad practice).