Does the main method belong to any class?
To do that, first, we need to create an object of “FirstClass” in the main method of the “SecondClass”. Once an object of the “FirstClass” is created, then we can invoke any method or attribute of the “FirstClass” within the “SecondClass” using that object.
Well, it depends, But usually main method put in sub class. There is quite big difference between in inheritance and shadowing. But you can put it subclass or super class. Remember main method is static.
Yes, you can compile and execute without main method by using a static block. However, after static block executes, you will get an error saying no main method found.
Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
It does belong to a class. Look at any hello-world implementation and it would be clear to you.
public static void main(String[] args) {
System.out.println("Hello World");
}
won't compile as it stands. You need to put class HelloWorld { ... }
around it, in which case you may say that the main method "belongs" to the HelloWorld
class.
However, since it's static, it does not belong to any particular object. There is an important difference between classes and objects that you need to get acquainted with when working with object oriented languages. Learning Java: Objects and Classes is a good starting point.
Yes. Every method or field must belong to a class (or interface/enum).
Every line of Java code (except import/package) lives in a class (or is a class/interface declaration). So does main
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With