A RetroSearch Logo

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

Search Query:

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

Java - private keyword

Java - private 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 −

Private Access Modifier - Private

Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.

Example

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

package com.tutorialspoint;

public class JavaTester {

   private 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.setFormat("XML");
      tester.print();
   }	   
}
Output
XML

Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.

So, 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 private access identifier. We've defined a private field in super class. If a field/method is private then it cannot be inherited by subclass.

Example
package com.tutorialspoint;

class Logger {
   private 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 class JavaTester extends Logger {   
   public static void main(String args[]) {
      JavaTester tester = new JavaTester();

      tester.setFormat("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