Miranda
Miranda

Reputation: 101

Class method vs main methods

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

Upvotes: 7

Views: 14546

Answers (6)

hfontanez
hfontanez

Reputation: 6188

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.

Upvotes: 1

Varun Achar
Varun Achar

Reputation: 15129

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.

Upvotes: 2

SJuan76
SJuan76

Reputation: 24895

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.

Upvotes: 6

shanet
shanet

Reputation: 7334

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!

Upvotes: 1

Lukas Knuth
Lukas Knuth

Reputation: 25755

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:

  1. The entrance-point of your application, so it will be the first called method and basic initialization things should be done here.
  2. 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.

Upvotes: 3

ek_ny
ek_ny

Reputation: 10243

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.

Upvotes: 5

Related Questions