If you have gone through our access specifier tutorial then you should be aware of how protected keyword works in Java. Just to rephrase, protected keyword is used when the classes within the same package or subclasses from other packages can access a member variable or member method or inner class.

If protected keyword is applied to a constructor then that constructor is only visible to the sub classes of this class in other packages.

Examples

Example:1 – Directly accessing protected constructor from other classes

The following program shows the use of protected keyword with constructor of a class then accessing this constructor from other classes in other packages.

Foo.java

package com.example;
 
public class Foo{
 
	protected int a = 10;
	
	protected Foo(){
	}
}

Main.java

package com.example;


public class Main {

	public static void main(String[] args) {
		Foo foo = new Foo();
		System.out.println(foo.a);
	}
}

FooSample.java

package com.sample;

import com.example.Foo;

public class FooSample {

	public static void main(String[] args) throws ReflectiveOperationException {
		Foo foo = new Foo(); //We shall see compiler error here as the protected constructor is invisible
	}
}

FooWorking.java

package com.sample;

import com.example.Foo;

public class FooWorking extends Foo{
	
	void bar(){
		System.out.println(a);
		
	}
	
	public static void main(String[] args) throws ReflectiveOperationException {
		FooWorking bw =new FooWorking();
		bw.bar();
	}
}
  • In the above code, the Main class is able to print the “a” member variable from class Foo as it is in the same package as Foo class.
  • The class “FooSample” is not able to print the value of “a” as the protected constructor is not visible to classes outside the package com.example.
  • The class “FooWorking” is able to access the member variable “a” from Foo class because it extends Foo and hence inherits the “a” member variable.

Example:2 – Accessing protected constructor from sub classes

A question arises as to what should be the requirement to make constructor as protected?
The answer is user might intend that no other classes outside his package can instantiate the class also he wants that the classes outside the package could extend his class. Marking a constructor as protected usually done while writing an Abstract class in java; it ensures for user to give more control over the constructor in abstract class
Abstract classes can’t be instantiated, but they can be extended.

In simple terms when we want to share common features of a parent class with the child classes, then we create parent class as abstract class which itself is too abstract to be used on its own.

You can take more reference of abstract class through our article on Abstract Class.

By default java compiler calls a non argument default constructor of abstract class.

Now how to call a Protected constructor in subclass; the answer is it can be called in subclass via Super() keyword.
We can see a practical example as below
package Numbers;

public class getNum
   {
   /**
    * constructor
    * @param firstnum.
    */
   protected getNum( int firstnum )
      {
      this.firstnum = firstnum;
      }

   private final int firstnum;

   }
////////////////////////////////

package Numerals;
import Numbers.getNum;

class Digits extends getNum
   {
   /**
    * constructor
    */
   public Digits()
      {
      super(10); // ok to use getNum protected constructor via super.
      }

   void myMethod()
      {
      getNum num = new getNum(3); // not ok, getNum would have to be public for this to work.
      Digits digi = new Digits(); // ok
      }

   }

Detecting protected constructors using static analysis

We can also ucdetector Eclipse plugin which can give suggestions on appropriate access specifiers to be used with variables, method and classes.

Related Posts

Making Constructors of a class Protected in Java admin Core Java
If you have gone through our access specifier tutorial then you should be aware of how protected keyword works in Java. Just to rephrase, protected keyword is used when the classes within the same package or subclasses from other packages can access a member variable or member method or...
If you have gone through our <a href="http://www.javaexperience.com/java-access-modifier-tutorial-defaultprivatepublicprotected/" title="Java Access Modifier tutorial – Default,Private,Public,Protected">access specifier tutorial</a> then you should be aware of how protected keyword works in Java. Just to rephrase, protected keyword is used when the classes within the same package or subclasses from other packages can access a member variable or member method or inner class. If protected keyword is applied to <a href="http://www.javaexperience.com/choosing-between-constructor-and-setter-methods/" title="Choosing between constructor and setter methods">a constructor</a> then that constructor is only visible to the sub classes of this class in other packages. <h2>Examples</h2> <h3>Example:1 - Directly accessing protected constructor from other classes</h2> The following program shows the use of protected keyword with constructor of a class then accessing this constructor from other classes in other packages. <strong>Foo.java</strong> 1 <strong>Main.java</strong> 1 <strong>FooSample.java</strong> 1 <strong>FooWorking.java</strong> 1 <ul> <li>In the above code, the Main class is able to print the "a" member variable from class Foo as it is in the same package as Foo class.</li> <li>The class "FooSample" is not able to print the value of "a" as the protected constructor is not visible to classes outside the package com.example.</li> <li>The class "FooWorking" is able to access the member variable "a" from Foo class because it extends Foo and hence inherits the "a" member variable.</li> </ul> <h3>Example:2 - Accessing protected constructor from sub classes</h2> <strong>A question arises as to what should be the requirement to make constructor as protected?</strong> The answer is user might intend that no other classes outside his package can instantiate the class also he wants that the classes outside the package could extend his class. Marking a constructor as protected usually done while writing an <a href="http://www.javaexperience.com/java-methods-of-an-abstract-class/" title="Methods of an Abstract class">Abstract class in java</a>; it ensures for user to give more control over the constructor in abstract class Abstract classes can’t be instantiated, but they can be extended. In simple terms when we want to share common features of a parent class with the child classes, then we create parent class as abstract class which itself is too abstract to be used on its own. You can take more reference of abstract class through our article on <a href="http://www.javaexperience.com/exhaustive-differences-between-abstract-class-and-interface/" title="Differences between Abstract class and interface">Abstract Class</a>. By default java compiler calls a non argument default constructor of abstract class. Now how to call a Protected constructor in subclass; the answer is it can be called in subclass via Super() keyword. We can see a practical example as below package Numbers; 1 <h2>Detecting protected constructors using static analysis</h2> <em>We can also <a href="http://www.javaexperience.com/eclipse-get-access-modifier-suggestions-using-ucdetector-plugin/" title="Get access modifier suggestions using Eclipse ucdetector plugin">ucdetector Eclipse plugin</a> which can give suggestions on appropriate access specifiers to be used with variables, method and classes.</em>
Adding and handling special characters in String in Java
Setting PATH, CLASSPATH and JAVA_HOME enviornment variables
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Latest posts by admin (see all)

Comments

comments