A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/java/public_keyword_in_java.htm below:

Java - public keyword

Java - public keyword

Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The four access levels are −

Access Control and Inheritance

The following rules for inherited methods are enforced −

Public Access Modifier - Public

A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Example

The following function uses public access control −

public static void main(String[] arguments) {
   // ...
}

The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Example

The following class uses public access control. We've used a public field as shown below −

package com.tutorialspoint;

public class JavaTester {

   public String format;

   public String getFormat() {
      return this.format;
   }

   public void setFormat(String format) {
      this.format = format;
   } 

   public void print() {
      System.out.println(this.format);
   }

   public static void main(String args[]) {
      JavaTester tester = new JavaTester();
	  tester.format = "XML";
   }	   
}
Output
XML

Here, the format variable of the Logger class is public, so this variable can be accessed directly using just a reference of the class Logger.

But as a best practice, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.

Following is another example of public access identifier. We've defined a public field in super class. If a field/method is public then it can be inherited by subclass.

Example
package com.tutorialspoint;

class Logger {
   public String format;

   public void print() {
      System.out.println(this.format);
   }
}

public class JavaTester extends Logger {   
   public static void main(String args[]) {
      JavaTester tester = new JavaTester();

      tester.format = "XML";
      tester.print();
   }	   
}
Output
XML

java_basic_syntax.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4