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
Related
If I had a HashMap such as in the following, how would I utilize it from another method? In this case, from Main?
public class Scratch {
public static void init() {
WordEnums words = new WordEnums();
List<String> bookList = new ArrayList<String>();
for (WordEnums.Book bookValues : WordEnums.Book.values()) {
bookList.add(bookValues.getDefinition());
}
HashMap<String, Object> wordDefinitions = new HashMap<>();
wordDefinitions.put("book", bookList);
}
public static void main(String[] args) {
List<String> book = (List<String>) wordDefinitions.get("book");
book.stream().forEach(s -> {
System.out.print(" ");
System.out.println(s);
});
}
I've tried moving it outside of init, something along the lines of what I could find here
But upon doing so, I get an error and am unable to access bookList within init.
Thanks
You can either define it as a static or create get method and get it through instance of the class it's in.
Java static:
https://www.javatpoint.com/static-keyword-in-java
Something to be aware of:
When you declare a member of a class static, it isn't associated with any instance of the class that you create. Given this information, you really have to think about how you want to structure your program.
If the method signature for init has to remain as you've written, you could make wordDefinitions a static member of your class and access it from init. However, if you do take this approach, be careful when you reference it. Remember that there is only one instance of wordDefinitions. Thus, you can only access it through referencing your class (Scratch) and not an instance of it.
The precise answer to the title question is "you can't". Here is why:
The variable named wordDefinitions does not exist outside of the init method. The scoping rules of Java say that it comes into existence every time you execute init and it no longer exists when init terminates. Thus accessing it from outside init has no meaning.
Similarly for bookList, which is why when you move the declaration of wordDefinitions outside of init, you have no access to bookList.
You would probably benefit from a review of Java's scoping rules. But for now, here's an approximate guide. For any data, you need to decide on its lifetime:
One copy that 'always' exists independent of any instances of the class: declare it static in the class.
A copy for each instance that exists for the lifetime of the instance: declare it non-static in the class (and perhaps initialize it in a constructor).
Data that only exists while a method is executing: declare it in the method body.
Given the above, you can access data "upwards" in the list but not "downwards".
This glosses over the distinction between a variable and the object it refers to, but I'm trying to keep it simple.
For your current problem, if you prefer to have all static methods (which seems to be something that introductory students do - are you taught that way? If so, I don't want to confuse matters by proposing differently) you should move the declaration of wordDefinitions to class scope with a static qualifier. Loading in the book list can still be done in init.
I mean we know that Static members should only belongs to the Class,and not part of the any object created from the class . but we can also access static methods via objects right? lets say getInstaceCount() is the static member of Class CharStack.
for example I can create object here and access Static member of CharStack :
CharStack stack1 = new Charstack(10);// declaring object
int count1 = stack1.getinstanceCount();//accessing Static member with the object
so above I can also access the static member of Charstack with object stack1,so my doubt is what is the exact use of Static member if its even accessible by its object ?similarly why instance variable of a class is not accessible by Class ?
A static method doesn't make any sense with respect of a specific instance of a class.
The fact that invoking a static method on an instance is allowed shouldn't fool you: it just a design error of Java language which makes no sense.
A static method doesn't have a this reference so it makes no sense to be able to invoke it on a specific instance.
in addition a static method is not polymorphic so in any case you can't exploit this fact by calling it on an instance
Short story: static methods make sense in certain situations, but you should always call them through the class, eg CharStakc.getInstanceCount() to clarify their intended behavior, since being allowed to invoke them through instances is just a bad choice which shouldn't be allowed at all.
similarly why instance variable is not accessible by Class ?
Say you have this class:
class Foo{
public static Bar barStatic;
public Bar barInstance;
public static void main(String[] args){
Foo foo=new Foo();
Bar barInstance=Foo.barInstance;//case 1
Bar barStatic=foo.barStatic;// case 2
.....
}
}
Now in case 1 you want to access some object's instance variable. But which object? One, more or no objects of the class Foo might be in the heap. But based on what should the runtime decide which object to choose (if one exists of course).
But in case 2, even though you say foo.barStatic compiler is "smart enough" to know that foo is an instance of Foo and interprets your foo.barStatic as Foo.barStatic when you compile the code. I definitely don't like this design, it's confusing. So, you should know that everything is fine under the hood, it's just during code design it doesn't complain although as others have noted, good IDE's will warn you to follow the preferred Foo.barStatic way.
The static variable gets memory only once in class area at the time of class loading.
It makes your program memory efficient (i.e it saves memory).
The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
I have a Computer Programming-K course at my high school, and we use Java as our language. I noticed that you seem to NEED to have the public *static* void main(String[] args) at the beginning of every script. Our main structure is this:
public class
( void main()
void input()
void process()
void output() )
And we have to make all void methods static, to be able to call one another, because we can't use a non-static main. Why? What does static mean in Java?
First and foremost, main being declared as public static void is mandated by the Java Language Specification:
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.
That's simply the way it is; without it, Java will not execute your script due to there being a lack of a main method.
It also doesn't matter where you put it - it could be in the middle of that class, at the top, at the bottom, or in a completely different file - so long as your program has a main method for it to actually run.
As for the meaning of static - well, that depends on the context.
If you're using static on a field (that is, a variable contained in a class), then there will only ever be one instance of that field.
If you're using static on a method (like main, or another method), then that is a class method, and does not require an instance of the object for it to be invoked and used. These particular methods shouldn't rely on the internal state of the class in which they're being invoked.
As an example, you'll get into a discussion about Integer.parseInt sometime later; this is a static method, which is tied to Integer, which doesn't require an instance of an Integer to invoke.
Next, don't think that the declaration of static methods is going to be commonplace for your code. To be frank, that represents purely procedural programming (that is, defining methods to do these specific things with no regard to state, instead of an object-oriented design that may or may not take into account state).
The only time you're ever forced to declare something to be static is if you're using it within a static context yourself. Since you don't create an instance of your class (through the new keyword), you won't be able to use any of the methods you've declared in it.
This will not compile, as main doesn't have a way to reference that method.
public class Foo {
public static void main(String[] args) {
invokeBar();
}
public void invokeBar() {
System.out.println("Yay, bar!");
}
}
The below will compile, since main does have a way to directly invoke that method:
public class Foo {
public static void main(String[] args) {
invokeBar();
}
public static void invokeBar() {
System.out.println("Yay, bar!");
}
}
Static means that you do not need to have an instance of a class in order to call that method.
static void main is just the specific function that Java requires, so that it knows where to begin running your code. Every program must contain one, and exactly one, static void main.
I noticed that you seem to NEED to have the 'public static void main(String[] args)' at the beginning of every script.
The reason for this is that when JVM runs your program it needs to be able to run it without creating an instance of your entry class containing main method. Sometimes your class containing main method may have constructors which needs arguments to create an instance of it then how would JVM know what values does it have to pass to create an instance of it on its own, which is why java forces you to make main as static method so that JVM doesnot need to worry about creating an instance of your main class to call the main method which is the entry point to your application.
And we have to make all voids static
This is an incorrect assumption. You need not make your void methods as static. There are 2 ways of calling your methods either through object of the class (these methods are called instance methods) or through the class variable(name) (these methods are called static methods). If you donot want to make your methods static then you need to create an instance of you class ad call your methods.
What does static mean in Java?
static is a modifier in Java . You can either use it for your instance variables or for methods or for inner classes. This keyword makes the resource(instance variables/methods/innerclass) a property of the underlying class and hence is shared across all the instances(objects) of the class.
I am new to JAVA, and I like to try and understand everything.
When accessing a static method "hero.returnHp()" in JAVA, I have the following:
hero Mike = new hero();
Mike.returnHp();
The program runs fine, but I notice that Eclipse has a warning stating, "The static method from the type hero should be accessed in a static way." When I accept the auto-fix, it changes "Mike.returnHp();" to "hero.returnHp();".
So I have two questions:
1) What is the advantage of this?
2) If I created two objects of the same type, how would I specify which one to return when accessing in a static way?
Thanks!
I would first like to point out what the keyword static means.
Static variables only exist once per class – that is, if you create a class with a static variable then all instances of that class will share that one variable. Furthermore, if it’s a public static variable, then anyone can access the variable without having to first create an instance of that class – they just call Hero.staticVariableName;
Static method/functions are stateless. That is, they act only on information (1) provided by arguments passed to the method/function, or (2) in static variables (named above), or (3) that is hard-coded into the method/function (e.g. you create a static function to return “hello” – then “hello” is hard-coded into the function).
The reason why Eclipse wants you to access static methods in a static way is because it lets you and subsequent programmers see that the method you’re accessing is static (this helps to prevent mistakes). The function will run either way you do it, but the correct way to do it is to access static functions in a static way. Remember that if you call a static method, no matter what instance variable you call it from (Tim.returnHp, Jim.returnHp, Mike.returnHp, whatever) you will call the same function from the hero class and you will see the exact same behavior no matter who you call it from.
If you created two objects of the same type then you COULD NOT specify which one to return when accessing in a static way; static functions/methods will refer to the entire Hero class.
Can you explain what you’re trying to do so that we can offer more specific feedback? It’s quite possible that returnHp() shouldn’t be static.
Is that “return hit points”? If it is, then you do NOT want it static because the number of hit points that a hero has is part of the hero’s state, and static methods are stateless. (Think of state like the current condition – alive, dead, wounded, attacking, defending, some combination of the aforementioned, etc.) I would recommend going into the Hero class and changing returnHp to a non-static method.
Now… I know you didn’t ask, but I would like to advise you of something:
Class names (such as Hero) should be capitalized. Instance variable names (such as mike) should be lowercase. This is a widely accepted naming convention and it will increase the readability of your code.
Jeff
A static method is one which belongs to a class but not to an object. In your example above, you have created an object Mike of class hero. The method returnHp() is static, and belongs to the hero class, not the hero objects (such as Mike).
You will likely get an IDE or compiler warning when you reference a static method from an object, because it should never be tied to that object, only to its class.
Based on the method name, I would guess it shouldn't be static.
class hero {
private float hp;
public float returnHp() { // Should NOT be "public static float ..."
return hp;
}
}
The JavaDocs on class members has a brief discussion on statics as well. You may want to check that out.
A static method is completely independent of any instances of the class.
Consider that this works, and does not result in a NullPointerException:
hero Mike = null;
Mike.returnHp();
(by the way, class names should start with a capital, and variable names be lowercased).
Here is another neat example: Being a static method, Thread.sleep always sleeps the current thread, even if you try to call it on another thread instance.
The static method should be called by class name, not through an instance, because otherwise it is very confusing, mostly because there is no dynamic dispatch as static methods cannot be overridden in subclasses:
hero Tim = new superhero(); // superhero extends hero
Tim.returnHp(); // still calls the method in hero, not in superhero
You are getting a compiler warning now, but many people say that this was a design mistake and should be an error.
It is part of the JVM spec.
You don't need to. A static method is common between instances of a class, your confusion arises from thinking it is an instance method.
static means a static way. One reason to use static is you can access it using class directly. that is its benefit. that is why main is always static. The entrance function don't need to create an instance first.
Actually if you search static in google, and understand it deeply. U will know when and why use static.
I have a class named Media which has a method named setLoanItem:
public void setLoanItem(String loan) {
this.onloan = loan;
}
I am trying to call this method from a class named GUI in the following way:
public void loanItem() {
Media.setLoanItem("Yes");
}
But I am getting the error
non-static method setLoanItem(java.lang.String) cannot be referenced from a static context
I am simply trying to change the variable onloan in the Media class to "Yes" from the GUI class.
I have looked at other topics with the same error message but nothing is clicking!
Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(Btw it would be better to use a boolean instead of a string containing "Yes".)
setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.
You may want to look into some basic object-oriented tutorials to see how static/instance members work.
setLoanItem() isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.
Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.
You probably want to pass in a media object on which to call the method:
public void loanItem(Media m) {
m.setLoanItem("Yes");
}
You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want
public void loanItem() {
this.media.setLoanItem("Yes");
}
or
public void loanItem(Media object) {
object.setLoanItem("Yes");
}
depending on how you want to pass that instance around.