Can I have only one public class in a Java class file?

Source: Internet
Author: User

Test code One:

1  Public class Test {2      Public Static void Main (string[] args) {3         4     }5}6publicclass  test1{7      8 }

Test results:

(public class Testtwo must be defined in its own class file)

Conclusion: Therefore, a class file can have only one public class.

Test code two:

1  Public class Test {2      Public Static void Main (string[] args) {3         4     }5public     class  innerclass{6         7     }8 }

Test results:

(Compiled by)

Where Innerclass is the test inner class.

By looking up information to know:

  Internal classes can have private access, protected access, public access, and package access. For example, if the member inner class inner is modified with private, it can only be accessed inside the external class, if it is modified with public, it will be accessible anywhere, if it is decorated with protected, it can only be accessed under the same package or inheriting the external class. ; If it is a default access, it can only be accessed under the same package. This is a bit different from the external class, and the outer class can only be decorated with both public and package access permissions. (Source: Java internal class details)

Conclusion:

    • The public class that is directly defined in the Java source file can have only one, and the class name must match the source file name.
    • An inner class can be understood as a member of an external class, and members can be decorated with public.

Can I have only one public class in a Java class file?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.