Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Extending class containing main method

Tags:

java

I have the following code as part of an assignment

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

public class Factorial extends Base{


}

My task is run the code and then explain the output.The name of the file is Factorial.java. The code runs without problem and Hello World is printed which to me is surprising. Before typing the code, I was thinking that it wont compile because the parent class, which is being extended should be in another file but now I am not so sure. Would appreciate soome clarification.

like image 476
user1107888 Avatar asked Jun 05 '13 20:06

user1107888


1 Answers

Java allows you to define multiple classes within a single .java file with the condition that you can have at most one public class and if you do then the name of that public class must match the name of the .java file. In your case, the class declared public is Factorial and hence your file name has to be Factorial.java.

The inheritance is working as usual here and the public static void main() is inherited by Factorial which is why you see your output on executing java Factorial.

like image 188
Ravi K Thapliyal Avatar answered Oct 06 '22 01:10

Ravi K Thapliyal