3

I'm taking AP Computer Science this year and my teacher says to use public class Main opposed to just class Main. When we asked her why not class Main she said that's just how AP Computer Science does it and didn't elaborate on it at all.

Nate Sedler
  • 103
  • 1
  • 2
  • 7
  • 2
    Defining your class as `public` allows other classes outside of the package (that your `public` class resides in) to see it. – Jacob G. Aug 24 '18 at 12:35
  • Maybe your teacher doesn't like packaging at all and keeps everything under the same package :) – Konstantin Yovkov Aug 24 '18 at 12:35
  • Because its your main class, the "front" class of your project its important that it is visible everywhere – Donatic Aug 24 '18 at 12:36
  • 1
    Can I suggest that you learn independently of this class? If the teacher cannot answer that, she clearly is just winging it. – Andy Turner Aug 24 '18 at 12:36
  • What a bad teacher. "We do this because we always did it that way". Sure, if you like, you can use COBOL. – Johannes Kuhn Aug 24 '18 at 12:37
  • I think it is not a duplicate of [what is the difference between `public class` and just `class`](https://stackoverflow.com/questions/16779245/what-is-the-difference-between-public-class-and-just-class), instead it is one of [Why doesn't the class containing main have to be public?](https://stackoverflow.com/questions/9640297/why-doesnt-the-class-containing-main-have-to-be-public) – deHaar Aug 24 '18 at 12:42
  • 1
    At the very least, I would hope a teacher might say "do you know, I don't actually know that. Why don't you try it without the public, and see if it works like that. And maybe see if you can do some research to see if you can find anybody discussing the difference". Teachers should be teaching you to learn independently, after all. – Andy Turner Aug 24 '18 at 12:54
  • Let me clarify by what she said about that's just how we do it. She was saying also how we'll learn about what it means later on in the course. She is a very good teacher, I've had her before. – Nate Sedler Aug 24 '18 at 15:04

1 Answers1

6

It is about how your class can be accessed. Using only class Main, the class can only be accessed from inside her package and the class self. Using public class Main, the class can be accessed from anywhere.
You can read more about modifiers at the javadoc:
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

ItFreak
  • 2,299
  • 5
  • 21
  • 45