Java public keyword example
- Details
- Written by Nam Ha Minh
- Last Updated on 19 August 2019   |   Print Email
In Java, the public keyword is an access modifier for class, method and variable:
- When a class is marked as public, it can be accessed from anywhere, including outside packages.
- When a method is marked as public, it can be invoked not only from the enclosing class, but also from outside classes.
- When a variable is marked as public, it can be accessed and updated from outside classes.
To summary, public is the access modifier that has least restriction on the object it modifies.
The following code example shows a public class which has a public method eat() and a public variable name:
public class Person { public String name; public void eat() { } }
Related keyword: protected and private. See all keywords in Java.
Related Topics:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments