A RetroSearch Logo

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

Search Query:

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

Java - protected keyword

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

Protected Access Modifier - Protected

Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example

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

package com.tutorialspoint;

public class JavaTester {

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

Example
package com.tutorialspoint;

class Logger {
   protected 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