0

I have just started learning Java and going through Heard up series. I see few examples where a class is created and has main in it and inside main, an object of the class is created. As main () is also part of the same class, is this ok? When you create a new Object, does it also create multiple copies of main () ? How does compiler decode this?

Sample code snippet explaining the problem

public class Hobbits {
    int size;

    public static void main(String [] args) {
        Hobbits h = new Hobbits[3];  
        // This is my point of concern. 
        // Here i create array of objects but each Object would have main class?
    }
}
0

3 Answers 3

1

The main-method is a static method. Static methods do not reference single objects, think of them as methods of a class instead of an object - they do not need any objects to work. Read this for further explanations.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to all of them for answering this. To be more precise, i was thinking as main () is inside class, every Object of that class has reference to main (). I think this is not right...
0

"but each Object would have main class?"

Your question is not so clear, but if you are asking if every class needs to have a main() method, then the short answer is NO. You can have a single main() in a separate class that calls all your other classes (Hobbit class, Wizard class, Elf class, etc.).

Comments

0

If your function/variable is static, it means there is only one instance of it, does not matter how many instances of your class you will create.

second thing, it will be more aesthetic, if you create separate class only for your main method

1 Comment

More than "aesthetic", I think having the main() in a separate class also marks the early beginnings of OP's first MVC. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.