I'm rather confused by the concept of making a class with methods, and having a main method with methods underneath.
What exactly are the differences here? How it one way better than the other way? What situations call for a method under the main rather than a class?
It would help me to understand a project - a basic Craps game which will contain a Shooter class, Die class, and a Craps class (which apparently contains the main).
You do not have "main" methods. All methods are a class method, the only difference is that 'static' methods (v.g., main) do not need that you instantiate a new object (via the 'new' statement) to use them.
In other words:
public class MyClass {
public static void myStaticMethod() {
}
public void myInstanceMethod() {
}
}
You can do
MyClass.myStaticMethod()
but in order to use myInstanceMethod you must create an object
(new MyClass).myInstanceMethod;
Usually you do the last thing as
MyClass myObject = new MyClass();
myObject.myInstanceMethod();
Note that you can also do
myObject.myStaticMethod();
but it is exactly the same than doing
myClass.myStaticMethod();
and the first way is considered poor style and usually causes a compiler warning.
#Miranda because with only static methods you lose all of the Object Oriented part, and you just end using Java as you would use plain C.
In the object, you have both the state and the methods. In the class you store both the object state and the methods. For instance, typically you can create a "Card" class, create a card "new Card('K', "Leaf")" and have methods to manipulate it ("uncoverCard()").
Once you have the reference to the object that you want, you use its methods and you know that you are only affecting this object, and that you are using the right version of the method (because you are using the method defined for this very class).
Switching to OO programming from procedural programming may seem difficult at the beginning. Keep trying, looking at tutorial code and asking for advice when needed and you'll soon get to understand it.
Basically it's a matter of separation. You create classes for reusability. If everything was in the main class then your code would not be maintainable. The main class is used as a starting point for your application. If you did everything in the main class you wouldn't be able to take advantage of all that object oriented programming affords you. You'll learn more about it as you get into the course. But basically each of the classes you will create will have single responsibility. Even the main class, whose responsibility is to run the program.
Good luck with your class by the way. Maybe it will give you an advantage in the casinos.
The entrance-point for a Java-Application is it's main-method:
public static void main(String[] args){
// Do stuff here
}
This method differs from others in the way that it's:
The entrance-point of your application, so it will be the first
called method and basic initialization things should be done here.
It's a static-method which makes it accessible without creating an
instance of the class holding it.
This static-thing is best illustrated as follows:
public class Test{
public int addOne(int number){
return number++;
}
public static int drawOne(int number){
return number--;
}
}
// Create our Int:
int value = 12;
// This will work because the method
// is a static one:
System.out.println( Test.drawOne(value) ); // Outputs 11
// This won't work because it's a non-
// static method:
System.out.println( Test.addOne(value) ); // Error
// But this will work:
Test ourTest = new Test();
System.out.println( ourTest.addOne(value) ); // Outputs 13
An Application written in Java will normally only have one main-Method, which declares the point where the Application first starts off.
If you want to do stuff with variables, objects, etc you'll want to create your own methods/classes but they won't be main-Methods.
First of all, method can't have another method inside it. Every method has to be part of a Class. The difference between a main method (actually the main method which you are talking about) and any other method is that execution of the program starts at the main method.
A method represents a functionality or a set of instructions that have been grouped together. And a class is a set of methods and variables that define an entity (like Shooter, Die).
So you'll have a Die class which will contain methods that will only contain die specific methods, a Shooter class with methods specific to Shooter and a Craps class, from where the game will begin, that utilizes the methods of the Die and Shooter classes to complete the game.
I'm sure some of the other guys here will be able to explain this much better than I can, but I'll give it a shot.
So, as you know, your main method is the sort of entry point to your program. It is the first thing executed. You can add other methods in the same class, but these methods are static methods as you can't instantiate a class that has your main in it (at least I don't think you can; I've never actually tried).
The purpose of making a class and defining methods is so that you can create objects out of that class. For instance, in your case, you create a Die class. You can then create Die objects from that class. Think of a class as a sort of model or mold that you create objects out of. Once you create these objects they each have their own data members (variables defined in the class). Lets say in your Die class you defined two variables, die1 and die2, each Die object you create will have a die1 and die2 variable, but each Die object can hold different values for these variables.
Now, lets say you create a method in the die class that modifies these variables (a setter method) and lets call it public void setDie1(int value) then you can modify the value of the die1 variable by calling that method on the Die object with something like myDieObject.setDie1(3).
To put this altogether, if you just put methods in the same class as your main method then you wouldn't be able to have multiple objects created from the same class.
This can be a tricky concept to figure out at first, but it will all clear up quickly as you learn more. I hope this helps!
The main method
This is the only method REQUIRED to run a Java application. The method MUST have a very specific signature public static void main(String[] args). The reason why it needs this specific signature is because the Java Virtual Machine (JVM) needs to find it in order to execute your program. The JVM is that Java runtime "thingy" you install on your computer to run programs. More correctly, the Java Runtime Environment (JRE) contains the JVM. The String[] args is 0 or more arguments the method accepts from the command prompt when executing a program. Simple programs often don't require any arguments being passed from the command prompt.
What might confuse beginner Java programmers, is that it seems that many projects out there have main methods in every .java file. This is not required. This is done so that each class could be run in isolation from its dependencies. In a project (application) only one class is required to have a main method.
Other methods
Methods other than the main method are optional. If you want, you could place 100% of your program logic inside of main. But, you can understand the problem with that. If you do that, your code will only be able to do a very specific sequence of steps. Back in the days prior to modular programming, this was the way it was done. So, if you needed to write a program that did something slightly different, you needed to write a new program. It is not very efficient, but it still works. Fast forward a few years after "modular programming" became a thing and now you have to write programs that have to react to events. For example, a user hovers the mouse over a button. The problem with events is that events are unpredictable. Not only you don't know WHEN events will occur, but also you cannot predict the ORDER in which they will occur. Therefore, having all the logic inside a single function (i.e. main) won't work and compiling a "different" sequence of steps inside main might not work also because you cannot predict the WHEN and HOW.
Methods allow you to encapsulate very small units of execution in a prescribed order. The assumptions is that, whenever a situation calls for it, the same sequence of steps must be executed. So, you modularize your code and extract those small sequences you know will always execute in that order and put it in some "method" so that you could call that sequence of steps when I needed.
Example
Simple program with no command-line arguments
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
When you execute the compiled unit from the command prompt, you will type java MyProgram and in the console you will see "Hello World!"
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello " + args[0]);
}
}
However, in the above program, if you don't provide an argument, it will throw an exception when executing. But, if you pass at least one argument, it will display the very first argument and ignore the rest. For example, java MyProgram Hector Fontanez will display "Hello Hector"
On both examples, the JVM called the main method for execution.
public class MyProgram {
public static void main(String[] args) {
showGreeting("Hello " + args[0]);
}
public static void showGreeting(String greeting) {
System.out.println(greeting);
}
}
In this last example, I created a function called showGreeting. Contrary to the main method, I as a programmer decided when and where to call this function, not the JVM. In the function, I extracted functionality I thought the method needs to execute in order to "show a greeting". I know my example has only one line. But you get the idea. As my program grows, I can call showGreeting from other parts of the program as many times I think, as a programmer, is necessary for my application to do the job it is required. Not only that, from the main method, the argument being passed will not necessarily the same as the argument that could be passed from another part of the program.
Lastly, you need to understand what are static and non-static methods, and also understand what public, protected, private, and default (no keyword) access modifiers do.
Related
What makes public static void main(String args[]) {} be the convention to test code instead of simply static {}?
class Test {
public static void main(String args[]) {
System.out.println("testing");
}
}
It seemingly has the same capabilities, you can instantiate owner class, use its methods, another classes, even send output as well:
class Test {
static {
System.out.println("testing");
}
}
Is there a standard reason to not use the small static {} to run your average test? Can I take it just as my choice/preference safely?
In other words, I'd like to find a case where you put a code in one that you couldn't (or shouldn't) put in another, that it wouldn't run or give unexpected result, etc.
I'd say the most prominent reason not to use static {} for such things is that you have little control over when it runs. static {} blocks run "when the class is initialized", which means at least four (watch out for the Spanish inquisition) detrimental things for this purpose:
It does not necessarily happen just because the class is loaded.
It does, on the other hand, happen just because you want an instance of the class or reference a static field from some other class, which is the main reason why you don't really want to put code with wide-ranging side-effects in static {} blocks.
It is also not guaranteed to not happen for such simple reasons as the Jar file being on your classpath. JVMs are free to run static {} blocks whenever they feel like it, as long as it is before any static references from the class from other code is made. "Before" could mean "at VM startup".
No VM implementation has any invocation arguments to run such code for you on request.
The purpose of static {} blocks is to initialize static class data (in possibly quite complex ways, of course), and from the preceding points you may be able to see why it's not particularly useful for anything else.
In java every application requires a main method which will be the entry point of the application. The main method required has the signature as follows:
public static void main(String[] args)
The difference between this method and the other one you suggested (besides the fact that your application needs a main method with this signature as an entry point) is that this is a method and takes the "String[] args" parameter. This parameter is where your arguments would go when running a program from the console.
Every java application can be run from the console and therefore it makes sense for every application to have a standard entry point method which will be able to take any special arguments.
Your static {} block is not necessarily a method or a function that can be called and therefore it can not be used as a entry point into your application. It takes no parameters and you have no control over when its code block will be run.
public class Basics {
Basics b = new Basics();
int instanceVariable = 0;
public void behavior() {
System.out.println("Print Something");
}
b.behavior(); // Why this line, b.behavior doesn't work?
public static void main(String[] args){
Basics b = new Basics(); /* Why are we allowed to create an
* object of same name again within
* the same class */
b.behavior(); // This line works
}
}
In the above class, I am able to create object . But I can't call b.behavior outside any class, but I am able to do that within a method. Why is that so? What is the difference?
public class Basics1 extends Basics{
Basics b = new Basics();
Basics1 b1 = new Basics1();
b = b1.instanceVariable; // I don't see error in this line, but previous line shows //error.
b1.instanceVariable // This line doesn't work
}
Why is b1.instanceVariable not working, instanceVariable is the base class instance variable.
You need to understand that a class is a "type definition", not a code block or sequence of statements.
You cannot just write arbitrary statements in a type definition.
Even so, "b1.instanceVariable" is not a statement. "b1.instanceVariable" doesn't mean anything in statement context.
A class defines variables and methods. b.behavior(); is a statement that cannot be on its own like that.
All code needs to be in methods, in field declarations (such as Basics b = new Basics(); in your example) or in "initializer blocks" (which are run as part of constructors or during class initialization).
This is just a syntax rule.
In other languages, you can have this kind of "raw code", to achieve various effects. What do you want to achieve?
run during compilation (like in Perl): Cannot be done in Java
run during constructor: use an init block
run during class loading: use a static init block
run when the program starts: put it in static void main
run during method invokation: put it in that method
Write code anywhere and expect it to execute is a form of procedural programming. In this form , you tend to loose context and soon the code becomes a spaghetti code --> methods getting called anywhere , anytime.
With OOP, you are trained to create objects with well defined methods which have a defined context. Just think, when would you like to get the b.behavior(); being called : Before initializing a class, after initializing the class, after execution of main or when the object is destroyed?
Interestingly, Java has defined syntaxes for each of the states.. You can wrap your code in { System.out.println("Hello World "); } and it will execute when the class is instantiate...Also you can use static { System.out.println("Hello World "); } and this will execute when class is loaded. But again, this is part of telling the JVM when to do it - an agreed upon syntax.. But without any marker around your code, when would you actually expect to run?
My assignment is to create a program that simulates a simple online shopping program.
we have to:
create a main menu with 3 options and then a submenu when selecting the 2nd option on the main menu.
I'm unsure how call a method from another class for example:
I have been given a method:
public void start() {
which is in the file "GroceryStore.java"
I am supposed to create a topMenu method which when the user inputs "1" calls to the method:
public void displayItems(){
^in file called "Stock.java"
which then prints out an array of items that online store has in stock. The array in the
Stock.java is
private SalesItem[] items;
Can anyone tell me how to do this? I have to do this for several things and I'm hoping I can apply the skeleton of this to the rest of the cases.
For now, I'm going to assume that Stock is an instance type(it sounds like an instance type), and It would make sense that your GroceryStore would have a reference to 1 or more Stock items.
Your Stocks will have to be instantiated with the new keyword. so
Stock myStock = new Stock(/*parameters for constructor*/);
after you do that, you can call the displayItems method of myStock like so
myStock.displayItems();
so start() is in the GroceryStore class.
So in a public static void main class you would go :
GroceryStore gs = new GroceryStore();
gs.start();
In your GroceryStore class you would have a new method which looks like (You may want to have the Stock stock = new Stock() line in the constructor of the GroceryStore object-- would make more sense:
Stock stock = new Stock();
public void topMenu(int parm){
if(parm==1)then{
stock.displayItems();
}
}
And then finally in the Stock class you have the displayItems method which may look like :
public void displayItems(){
for(int i=0;i<items.length;i++){
SalesItem temp = items[i];
System.out.prinlnt(temp.toString());//or this may be temp.getName() or whatever returns a string from this SalesItem object - I dont know what it looks like - you never said!
}
}
It is however essential you actually understand what is going on here not just copy paste and run?! This wont actually do anything anyway until you have a call to the topMenu method passing it 1, so you will need to workout how you are going to interact with your gs object whether its by keyboard input, mouse click on a gui or something else :)
To call a method outside the current instance you have multiple options:
make the method static (so that it won't be attached to any particular instance) and call it through MyClass.method(), this has sense if it is a stateless object, mostly an utility method
create a static instance variable that can be accessed (so method is not static but the specific object is), then call it through SomeClass.stock.method(), this has sense when you want a single object of a specific type throughout the program
create a normal instance variable inside the class from which you want to call the method (this has sense just if the object contained is used in a HAS-A relationship). Then you call it simply doing this.stock.method() (you can omit this)
You need to tell the compiler where to get the methods from if the method is not in the same class. The best way of doing this would be to create an object that refers to the class you're trying to reach (using the New Java keyword and the appropriate syntax, i.e. ClassName objectName = new ClassName() - you may want to include any parameters you may have).
Have a look at this other StackOverflow answer - the user had a question very similar to yours, so it may help.
Also, there is a pretty good tutorial on objects and classes on TutorialsPoint. I suggest you have a look at it and give it a go. Try understanding the concept behind what you're trying to achieve first - I can guarantee you it will help later on as this is a very fundamental concept in OO programming.
I'm the product of some broken teaching and I need some help. I know that there is this thing called the "main method" in Java and I'm sure other programming languages. I know that you need one to make your code run, but how do you use it to make your run? What does it do and what do you need to have it put in it to make your code run?
I know it should look something like this.
But almost nothing more.
static void main(String[] args){
}
Breaking this down, point-by-point, for the general case:
All Java applications begin processing with a main() method;
Each statement in the main executes in order until the end of main is reached -- this is when your program terminates;
What does static mean? static means that you don't have to instantiate a class to call the method;
String[] args is an array of String objects. If you were to run your program on the command line, you could pass in parameters as arguments. These parameters can then be accessed as you would access elements in an array: args[0]...args[n];
public means that the method can be called by any object.
its the entry point for any java program, it does whatever you tell it to do. all you need to do is declare it in one of your source java files and the compiler will find it.
Firstly it should be public static void main(String[] args){...}.
It must be public
Take a look at The main method
The JVM will look for this method signature when it runs you class...
java helloWorld.HelloWorld
It represents the entry point for your application. You should put all the required initialization code here that is required to get your application running.
The following is a simple example (which can be executed with the command from above)
package helloWorld;
public class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Summary
void means the method returns no value. String[] args represents a string of arguments in an Array type that are passed to the program. main is the single point of entry in to most Java programs.
Extended
Glossing over why it should be public static void... (You wouldn't build a door without a doorknob), methods (equivalent of functions (or subs) in other languages) in Java have a return type. It just so happens that the main method in Java has to return void. In C or C++, the main method can return an int and usually this indicates the code status of the finished program. An int value of 0 is the standard for a successful completion.
To get the same effect in Java, we use System.exit(intValue)
String[] args is a string array of arguments, passed to the main function, usually for specific application use. Usually these are used to modify a default behavior or for flags used in short command line executable applications.
main just means to the JVM, start here! Same name in C and C++ (and probably more).
when you execute your class, anything in the main method runs.
You should have a main class and a main method. And if you want to find something in the console, you need have one output command at least in the method, like :
System.out.println("Hello World!");
This makes the code running lively.
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.