Home » Java Public Keyword

Java Public Keyword

by Online Tutorials Library

Java public keyword

A Java public keyword is an access modifier. It can be assigned to variables, methods, constructors, and classes. It is the most non-restricted type of access modifier.

Points to remember

  • The public access modifier is accessible everywhere. So, we can easily access the public inside and outside the class and package.
  • If you are overriding any method, overridden method (i.e., declared in the subclass) must not be more restrictive. So, if you assign public to any method or variable, that method or variable can be overridden to sub-class using public access modifier only.
  • If a program contains multiple classes, at most one class can be assigned as public.
  • If a class contain a public class, the name of the program must be similar to the public class name.

Examples of public keyword

Example 1

Let’s see an example to determine whether public variable and method is accessible or not outside the class. Here, we also try to create an instance of constructor outside the class.

Output:

Try to access a public variable outside the class  Try to access a public method outside the class  Try to create the instance of public constructor outside the class  

Example 2

Let’s see an example to determine whether public variable and method is accessible or not outside the package. Here, we also try to create an instance of constructor outside the package.

Output:

Try to access a public variable outside the package  Try to access a public method outside the package  Try to create the instance of public constructor outside the package   

Example 3

Let’s see an example to determine whether the public method is overridden to sub-class using public access modifier.

Output:

Try to access the overridden method  

Example 4

Let’s see an example to determine whether the public method is overridden to sub-class using private access modifier.

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:   Cannot reduce the visibility of the inherited method from A  

Example 5

Let’s see an example to determine whether the public method is overridden to sub-class using default access modifier.

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:   Cannot reduce the visibility of the inherited method from A  

Example 6

Let’s see an example to determine whether the public method is overridden to sub-class using protected access modifier.

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:   Cannot reduce the visibility of the inherited method from A  
Next TopicJava Keywords

You may also like