6

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.

6
  • 1
    Homework? Anyway, nothing strange here. Why are you confused? Commented Jun 5, 2013 at 20:43
  • 2
    I don't get it, do you mean Factorial is in the same file as Base? How do you "run the code"? Commented Jun 5, 2013 at 20:43
  • 1
    So the command you use to run it is "java Factorial"? Commented Jun 5, 2013 at 20:44
  • You can have more than one java class in a java file. Here is an explanation stackoverflow.com/questions/968347/… Commented Jun 5, 2013 at 20:46
  • 1
    You can have more than one class in a file but only one public class. More info Commented Jun 5, 2013 at 20:47

2 Answers 2

12

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.

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

Comments

1

You can have more than one class in the same file, but only one public , as Base isn't a public class, but it's not a recommended practice.

3 Comments

And am I right in assuming that since the extending class inherits the main function from the parent class, it is executed as soon as the program runs?
@user1107888 yes, as Factorial extends Base it also inherits the main method.
@user1107888 the main method is static; it is associated with the class itself. Since Factorial extends Base and Factorial does not define main, the main "seen" by Factorial is the one from base.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.