×

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A member's access is declared to be public with the Java keyword public. All other classes can see members of the public class. This implies that a public field or method can be accessed by any other class. In addition, public fields can be changed by other classes unless they are marked as final.

It is recommended to make fields private and to only grant public access to the methods and final fields that establish the public constants for the class. This aids with encapsulation and information hiding since it enables you to update a class' implementation without having an impact on users who only access the class' public API.

Any class may access a stated public class, method, function Object () {[native code]}, interface, etc. As a result, any Java Universe class can access properties, methods, and blocks declared inside a public class. A public class named Length that preserves private instance fields with the names units and is an example of an immutable class.

Important Points to Remember about public keyword:

  • Everywhere has access to the public access modifier. As a result, we have easy access to both the class and package's public.
  • Any method that is being overridden must not be more restrictive than the original method, which must be stated in the subclass. Therefore, if you give a method or variable the public access modifier, only the public access modifier can be used to override it in a subclass.
  • A program may only designate one class as public if it has many classes.
  • The name of the program must be like the name of the public class if a class contains one.

Examples of Public Keyword

Here is an illustration of how to tell whether a public variable and method is used outside of the class. We also attempt to make a function Object () {[native code]} instance outside of the class.

class HH {  
    public String msg="outside the class the public variable is accessed";
     String info;
     public void disp()  
     {  
         System.out.println("outside the class the public variable is accessed");
         System.out.println(info);
     }  
Public HH (String info)  
     {  
         this.info=info;
     }  
} 
public class PublicEx1 {  
    public static void main (String [] s) {  
HHh=new HH ("outside the class trying to create the instance of public constructor ");
       System.out.println(h.msg);
h. disp();
    }  
}  

Output:

outside the class the public variable is accessed
outside the class the public variable is accessed
outside the class trying to create the instance of public constructor

Example 2:

An illustration of how to check whether a public variable or method is usable outside of the package. Here, we also attempt to make a function Object () {[native code]} instance outside of the package.

class HH {  
    public String msg="outside the package the public variable is accessed";
     String info;
     public void disp()  
     {  
         System.out.println("outside the package the public variable is accessed ");
         System.out.println(info);
     }  
     Public HH (String info)  
     {  
         this.info=info;
     }  
} 
//save by PublicEx1.java  
package com. Javalang;
import com.java. HH;
public class PublicEx2 {  
    public static void main (String [] s) {  
HHh=new HH ("outside the package trying to create the instance of public constructor ");
       System.out.println(h.msg);
h. disp();
    }  
}  

Output:

outside the class the public variable is accessed
outside the class the public variable is accessed
outside the class trying to create the instance of public constructor

Example 3:

An illustration of how the public access modifier can be used to identify whether a public method is overridden by a subclass.

class HH
{  
    public void msgs ()  
    {  
        System.out.println("try to do it");
    }  
}  
class PublicEx3 extends HH {  
    public void msgs ()  
{  
    System.out.println("accessing the overridden method");
}  
public static void main (String [] s) {  
    PublicEx3 h=new PublicEx3();
h. msgs();
}  
}  

Output:

accessing the overridden method

Example 4:

An illustration of how the private access modifier can be used to identify whether a public method is overridden by a subclass.

class AA
{  
    public void msgs ()  
    {  
        System.out.println("Try it access");
    }     
}  
class PublicEx4 extends AA {  
    private void msgs ()  
{  
    System.out.println("accessing the overridden method");
}  
public static void main (String[] s) {  
    PublicEx4 p=new PublicEx4();
p. msgs();
}  
}  

Output:

Error: Unresolved compilation problem

Example 5:

An illustration of using the default access modifier to check whether the public function is overridden by the subclass.

class AA
{  
    public void msgs ()  
    {  
        System.out.println("Try it access");
    }     
}  
class PublicEx4 extends AA {  
    void msgs ()  
{  
    System.out.println("accessing the overridden method");
}  
public static void main (String[] s) {  
    PublicEx4 p=new PublicEx4();
    p. msgs();
}  
}  

Output:

Error: Unresolved compilation problem

Example 6:

An illustration of how the protected access modifier can be used to identify whether a public method is overridden by a subclass.

class AA
{  
    public void msgs ()  
    {  
        System.out.println("Try it access");
    }     
}  
class PublicEx4 extends AA {  
protected void msgs ()  
{  
    System.out.println("accessing the overridden method");
}  
public static void main (String[] s) {  
    PublicEx4 p=new PublicEx4();
    p. msgs();
}  
}  

Output:

Error: Unresolved compilation problem

Related Topics

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.