Why cant we call nonstatic method from static method? [duplicate] - java

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

Related

Accessing Non static members from a static method. I get error as - cannot make a static reference to a non-static field [duplicate]

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
}

Why is an object needed to refer to a class member inside of a static method? [duplicate]

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."

non static to static method from another class [duplicate]

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.

Is t1 static or non-static? [duplicate]

This question already has answers here:
In Java, are variables declared inside static methods themselves static?
(5 answers)
Closed 6 years ago.
Is t1 static or non-static?
class Test {
void display() {
System.out.println("hello");
}
public static void main(String a[]) {
Test t1 = new Test(); //object created
t1.display();
}
}
t1 is a local variable and local variables are not static since they live in the scope of the method while a static variable/field exists independently of the method execution.
A static variable/field must be declared outside methods.
It is not itself static, though it exists solely within a static context. The static descriptor only applies to class-level entities. Consider this class (a simplified version of the built in java.lang.Math class):
class EasyMath {
public static final double PI = 3.17;
public static int quadruple(int i) {
int num = i * 4;
return num;
}
}
You would reference the value of PI directly, using EasyMath.PI. It's a class variable. It belongs directly to the EasyMath class, not to instances of the class.
Likewise, you would reference the quadruple method from the class as well: EasyMath.quadruple(6). That's because the method is static, it belongs directly to the class.
Note that the quadruple method defined a local variable named num. However, you're not able to reference that using EasyMath.num. It does not belong to the class.
It's scoped locally to the static quadruple method, so it's available for use only in that method, and nowhere else. Another static method would not be able to see it or reference it. Likewise, if there were any instance methods, they would not be able to see it either. A local variable can never be static.

What is the purpose of static keyword in this simple example? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should a method be static?
Usually when writing a static method for a class, the method can be accessed using ClassName.methodName. What is the purpose of using 'static' in this simple example and why should/should not use it here? also does private static defeat the purpose of using static?
public class SimpleTest {
public static void main(String[] args) {
System.out.println("Printing...");
// Invoke the test1 method - no ClassName.methodName needed but works fine?
test1(5);
}
public static void test1(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
public void test2(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
private static void test3(int n1) {
System.out.println("Number: " + n1.toString());
}
}
I had a look at a few tutorials. E.g. http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
My understanding of it is that instead of creating an instance of a class to use that method, you can just use the class name - saves memory in that certain situations there is no point in constructing an object every time to use a particular method.
The purpose of the static keyword is to be able to use a member without creating an instance of the class.
This is what happens here; all the methods (including the private ones) are invoked without creating an instance of SimpleTest.
In this Example,Static is used to directly to access the methods.A private static method defeats the purpose of "Data hiding".
Your main can directly call test1 method as it is also Static,it dosn't require any object to communicate.Main cannot refer non-static members,or any other non-static member cannot refer static member.
"non-static members cannot be referred from a static context"
You can refer This thread for more info about Static members.
static means that the function doesn't require an instance of the class to be called. Instead of:
SimpleTest st = new SimpleTest();
st.test2(5);
you can call:
SimpleTest.test1(5);
You can read more about static methods in this article.
A question about private static has already been asked here. The important part to take away is this:
A private static method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state? -eljenso
static means that the method is not associated with an instance of the class.
It is orthogonal to public/protected/private, which determine the accessibility of the method.
Calling test1 from main in your example works without using the class name because test1 is a static method in the same class as main. If you wanted to call test2 from main, you would need to instantiate an object of that class first because it is not a static method.
A static method does not need to be qualified with a class name when that method is in the same class.
That a method is private (static or not) simply means it can't be accessed from another class.
An instance method (test2 in your example) can only be called on an instance of a class, i.e:
new SimpleTest().test2(5);
Since main is a static method, if you want to call a method of the class without having to instantiate it, you need to make those methods also static.
In regards to making a private method static, it has more readability character than other. There isn't really that much of a difference behind the hoods.
You put in static methods all the computations which are not related to a specific instance of your class.
About the visibility, public static is used when you want to export the functionality, while private static is intended for instance-independent but internal use.
For instance, suppose that you want to assign an unique identifier to each instance of your class. The counter which gives you the next id isn't related to any specific instance, and you also don't want external code to modify it. So you can do something like:
class Foo {
private static int nextId = 0;
private static int getNext () {
return nextId ++;
}
public final int id;
public Foo () {
id = getNext(); // Equivalent: Foo.getNext()
}
}
If in this case you want also to know, from outside the class, how many instances have been created, you can add the following method:
public static int getInstancesCount () {
return nextId;
}
About the ClassName.methodName syntax: it is useful because it specifies the name of the class which provides the static method. If you need to call the method from inside the class you can neglect the first part, as the name methodName would be the closest in terms of namespace.

Categories

Resources