In Java, a class can be marked as public
, which means that it can be accessed from anywhere within the same package or from other packages. A Java source file (a file with a .java
extension) can contain multiple classes, but only one of these classes can be marked as public
.
This means that a single Java source file can contain at most one public
class. However, a Java project can contain multiple source files, each of which can contain its own public
class.
Here's an example of a Java source file with a single public
class:
public class MyClass { // class definition goes here } class MyOtherClass { // class definition goes here }Sourceww:w.lautturi.com
In this example, the MyClass
class is marked as public
, while the MyOtherClass
class is not. This means that the MyClass
class can be accessed from other source files, but the MyOtherClass
class can only be accessed within the same source file.
It is generally recommended to limit the use of public
classes to a small number, and to use private
or protected
visibility for most classes to improve encapsulation and modularity. This can help to make your code more maintainable and easier to understand.