This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
New to Java, trying to figure out how to resolve this issue.
boolean myBool = G(A,n,m,0);
For some reason it isn't like this line. Why won't it let me call this simple function? Both main() and G() are part of class C().
A non static method belongs to a specific instance of a class, while a static method belongs to the class itself. Inside main, which is a static method, you cannot reference non-static methods without having a specific object to run them. E.g.:
boolean myBool = new C().G(A,n,m,0);
However, if the class has no interesting state, or it's state does not effect the method G, you should define G as static.
It's likely because you didn't include static in the definition of the G() method.
Main() is a static method, and since static things run before non static things do, static things can only call/use static things.
Note that your Main() doesn't require you to make a C object. It's the entry point to the program, and it doesn't make sense if you have to first make an object in order to run your program - where would you make that object from?
If you want to make non-static calls, create objects of the corresponding class.
Related
This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 2 years ago.
I've learned that I should use Object(instance) for using instance field in static method.
For example:
INSTANCE FIELD(==speed)
that is declared in public class Car, should be used through Object in static method (ex. 'public static void main(String[] args) )
like this.
Car myCar = new Car();
myCar.speed = 60;
So, the reason I should use object is because static method is located in CLASS and for being shared to objects, but on the other hand, instance field is just Frame that is not substance?
For using this instance field in static method, do I have to make the instance that is called 'object'?
In other words, is this process right?:
instance field -> OBJECT( substantialization) -> static method.
I'm wondering what I understood
static methods are used for 3 reasons:
"stateless" methods. A good example of this would be Math.sin
Global "singletons": singleton is in quotes because the singleton pattern is not used everywhere in java. An example of where it is could be Runtime.getRuntime() an example of where it isn't might be Thread.getUncaughtExceptionHandler (implicit singleton)
Program entry point (public static void main) : It makes sense for a program to start outside of an object context (rather than innside)
This question already has answers here:
Difference between Static methods and Instance methods
(10 answers)
Closed 4 years ago.
Whenever I have to call a method from another class, I first create an object and then call it through the object. But while I was writing some code, I mistakenly wrote classname.methodname(); and it worked.
I would usually write,
classname obj = new classname();
obj.methodname();
Here is the actual code:
Class 1
public class Dataset {
public static List<ECCardData> getDataset() {
//Code
}
in Class 2
List<ECCardData> dataset = Dataset.getDataset();
I noticed that the methodname() was static. Was that the reason?
Yes, for static methods (with suitable access modifier) you can call directly with your class by
YourClass.yourMethod();
and this way, too
YourClass anObject = new YourClass();
anObject.yourMethod();
Happy coding.
I hate answering my question, but I found the correct answer.
When a method is declare static, only one instance of that method will exist. When you create an object a new instance of the method is created, which is not possible for a static method. Therefore you use the class name.
classname.methodname(); //only one instance
classname obj;
obj.methodname(); //instance with obj as Object(IDE gives warning, should not be allowed, ideally)
The basic paradigm in Java is that you write classes, and that those
classes are instantiated. Instantiated objects (an instance of a
class) have attributes associated with them (member variables) that
affect their behavior; when the instance has its method executed it
will refer to these variables.
However, all objects of a particular type might have behavior that is
not dependent at all on member variables; these methods are best made
static. By being static, no instance of the class is required to run
the method.
You can do this to execute a static method:
classname.staticMethod();//Simply refers to the class's static code But
> to execute a non-static method, you must do this:
>
> classname obj = new classname();//Create an instance
> obj.nonstaticMethod();//Refer to the instance's class's code
This question already has answers here:
How do I create a static local variable in Java?
(8 answers)
Closed 6 years ago.
I know that in C, when the keyword static is used on a local variable, it causes that variable to remain initialized between function calls (i.e. when the variable goes out of scope). For example:
int myFunction() {
static int i = 3;
i++;
return i;
}
If myFunction() is called twice, it will return 4 the first time and 5 the second time (because i keeps its value between the two calls rather than being reinitialized the second time).
My question is this: does Java have an equivalent keyword to static in C? Java also has the keyword static, but it is used completely differently than in C.
Not exactly, but a private static class level variable will almost do the same thing.
But
it will be visible to all other methods of the class as well
it will be initialized not on first method call, but when the class itself is loaded
I suppose that is workable.
All variables in a method are local to the function and placed on the stack. The closest you have is a static variable in a class.
If you make the variable private and place the method in a class of it's own you will achieve much the same result.
(With a private constructor)
It's somewhat similar to the private keyword, as in C a static global variable or a function is visible only in the file it's declared in...
So that's probably the closest you will find :)
No, because all methods and functions are bound to classes in Java, so there is no "global space" as there is in C. The static keyword in Java has different semantics.
See the docs for static and this post for more detail on the differences.
Java uses static in a different manner. To get the same result you want here, you should use a private field instead.
This question already has answers here:
How come invoking a (static) method on a null reference doesn't throw NullPointerException?
(5 answers)
Closed 8 years ago.
Recently I was going through a page on javarevisited and found a block of code which asked the readers to determine what would be the output for it...
Though I got the output I am not satisfied with the result (WHICH CAME OUT TO BE "Hello") since I don't know how a static member is accessed from a null reference. What's happening in the background?
public class StaticDEMO {
private static String GREET = "Hello";
public static void main(String[] args) {
StaticDEMO demo = null;
System.out.println(demo.GREET);
// TODO code application logic here
}
}
This works because the JVM knows you are trying to access a static member on a specific class. Because you had to declare demo as a specific class (in this case a StaticDEMO), it knows to use that to find GREET.
To be clear, you don't run into this often (I actually had to type this code in to verify it, I can't say I've ever seen this). Mainly, it's good practice to always refer to static fields by their class, not an object instance (which may be null, as we can see!).
Meaning, prefer this:
System.out.println(StaticDEMO.GREET);
EDIT
I found a reference to this in the Java Specification: Chapter 15, Section 11: Field Access Expressions.
Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access
The following program demonstrates that a null reference may be used to access a class (static) variable without causing an exception
[example not shown here for brevity]
Any method which is being decorated as static in Java means, that method is a class level memeber. That means, you do not need an object to accss static members. The static method/variable is maintained by the Class itself, and not by any instance of the class. Here in your example, the compiler already knows that the member is static member and it doesn't need any instance to access that static method.
Static members are stored with the Class, not with any specific instance of it. So, it doesn't matter that the instance is null - the member from the Class is still be accessible.
The JVM simply ignores null, because GREET is a class field and demo is irrelevant reference to refer Class field.
Static method not needed object reference to call it so you can call it even reference to the object is null.
I'm learning java and now i've the following problem: I have the main method declared as
public static void main(String[] args) {
..... }
Inside my main method, because it is static I can call ONLY other static method!!! Why ?
For example: I have another class
public class ReportHandler {
private Connection conn;
private PreparedStatement prep;
public void executeBatchInsert() { ....
} }
So in my main class I declare a private ReportHandler rh = new ReportHandler();
But I can't call any method if they aren't static.
Where does this go wrong?
EDIT: sorry, my question is: how to 'design' the app to allow me to call other class from my 'starting point' (the static void main).
You simply need to create an instance of ReportHandler:
ReportHandler rh = new ReportHandler(/* constructor args here */);
rh.executeBatchInsert(); // Having fixed name to follow conventions
The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to create an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling ReportHandler.executeBatchInsert, there isn't enough context.
It's really important that you understand that:
Instance methods (and fields etc) relate to a particular instance
Static methods and fields relate to the type itself, not a particular instance
Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of that person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).
Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a vital distinction to understand, and you'll have all kinds of problems until you've understood it.
Please find answer:
public class Customer {
public static void main(String[] args) {
Customer customer=new Customer();
customer.business();
}
public void business(){
System.out.println("Hi Harry");
}
}
Java is a kind of object-oriented programming, not a procedure programming. So every thing in your code should be manipulating an object.
public static void main is only the entry of your program. It does not involve any object behind.
So what is coding with an object? It is simple, you need to create a particular object/instance, call their methods to change their states, or do other specific function within that object.
e.g. just like
private ReportHandler rh = new ReportHandler();
rh.<function declare in your Report Handler class>
So when you declare a static method, it doesn't associate with your object/instance of your object. And it is also violate with your O-O programming.
static method is usually be called when that function is not related to any object behind.
You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.
A static method means that you don't need to invoke the method on an instance. A non-static (instance) method requires that you invoke it on an instance. So think about it: if I have a method changeThisItemToTheColorBlue() and I try to run it from the main method, what instance would it change? It doesn't know. You can run an instance method on an instance, like someItem.changeThisItemToTheColorBlue().
More information at http://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods.
You can think of a static member function as one that exists without the need for an object to exist. For example, the Integer.parseInt() method from the Integer class is static. When you need to use it, you don't need to create a new Integer object, you simply call it. The same thing for main(). If you need to call a non-static member from it, simply put your main code in a class and then from main create a new object of your newly created class.
You cannot call a non-static method from the main without instance creation, whereas you can simply call a static method.
The main logic behind this is that, whenever you execute a .class file all the static data gets stored in the RAM and however, JVM(java virtual machine) would be creating context of the mentioned class which contains all the static data of the class.
Therefore, it is easy to access the static data from the class without instance creation.The object contains the non-static data
Context is created only once, whereas object can be created any number of times.
context contains methods, variables etc. Whereas, object contains only data.
thus, the an object can access both static and non-static data from the context of the class
Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.methodname();
But if you write the method as static then you won't need to create object and you will be able to call the method using methodname(); from main. And this will be more efficient as it will take less memory than the object created without static method.
Useful link to understand static keyword
https://www.codeguru.com/java/tij/tij0037.shtml#Heading79