×

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

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.