Java class containing the main method

I have the following code as part of the destination

class Base { public static void main(String[] args){ System.out.println("Hello World"); } } public class Factorial extends Base{ } 

My task runs the code and then explains the output. The name of the file is Factorial.java . The code works without problems, and Hello World prints, which is surprising to me. Before entering the code, I thought that it would not compile, because the parent class that is expanding should be in a different file, but now I'm not sure. Will appreciate the clearance.

+6
source share
2 answers

Java allows you to define several classes in a single .java file with the condition that you can have no more than one public class and , if , then you must have the name of this public class with the name of the .java file. In your case, the class declared by public is Factorial , and so your file name should be Factorial.java .

Inheritance works as usual, and public static void main() inherited by Factorial , so you see your result when java Factorial executed.

+12
source

You can have more than one class in one file, but only one public, since Base not a public class, but this is not recommended.

+1
source

Source: https://habr.com/ru/post/946622/


All Articles