Access Modifier in Java with Example
Good code is its own best documentation. As you’re about to add a comment, ask yourself, “How can I improve the code so that this comment isn’t needed?” Improve the code and then document it to make it even clearer.
Welcome back to Java Tutorials, with an excitement to move one more step in Java learning. Today I am sharing in this blogpost/tutorials about Java Access Modifiers.
Access modifier (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation (Packing the data and function into single components/ Hiding the data member and member functions) of components.
Types of Access Modifiers:
- Access Control Modifiers
- Non Access Modifiers
Access Control Modifiers: Java has a capability to access the control of/regulate the: classes, variable, methods, constructor, subclass, packages and interface using below four keywords in a definition and change their meaning. It also helps the program to have a structure proper scoping of a method/function and variables declared by a Coders.
Order of Access Control specifiers: Most to Least order of Access Control Specifiers.
Public > Protected > Default (Package Private)> Private
There are four types of Access Control Modifiers:
- Default : When no modifier is used then member variables and methods are accessible in same class or in any other class in same package.
- Public : Accessible to any class where ever it is inherited or imported
- Protected : Accessible in same package and also in subclass in some other package
- Private: Accessible only in class
Default Access Control Modifiers:
Default Access Control Modifiers have the access control/Scoping will be visible only to code inside the class as well as in the same package
In Brief : Default access Modifier can also be called as private to the package level, can access class, inner class , member variables, methods/member functions, constructor for which the default access is assigned to. Note: Constructor will be visible to only the same package.
Example:
Now we are going to create two package one is pack1 and second with name pack2. Here we are going to create one class Employee.java in package pack1 without any modifier from private, public or protected.
package pack1; class Employee{ private int employeeId; private String employeeName; private String designation; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } }
Now we are going to create second class “TestDefaultAccessModifierAsPackagePrivate.java” and we are going to create a object of Employee.
package pack2; import pack1.*; public class TestDefaultAccessModifierAsPackagePrivate { Employee emp = new Employee(); //compilation error }
Here going to post one snap taken from eclipse.
Above compilation error stating to “Change visibility of Employee to ‘public'” . It shows that Employee class can not be accessed outside the same package. In the same fashion Subclass(Suppose ChildEmployee.java) can not access the member variable and member function of Employee class if this SubClass is in some other package.
Note:
1- While Subclass in same package can access all the member variable and method from the SuperClass.
2- In interface default modifier is counted as public.In interface the member variable are implicitly public static final and methods in interface are default by final; modifiers other than public are forbidden in Interface.
3- Enumeration constants are always public.
Protected Access Control Specifiers: Protected Access Control specifiers is similar as default except one difference, it allows sub- class (Inside & outside the packages) to inherit the member variables, member function, and constructors outside the same package.
**Protected Access Control specifiers applies only to inheritance.
Explanation: If a subclass outside the package has a reference to an instance of the superclass, the subclass can’t access the protected method using that superclass references. The only way subclass can access that method is by inheriting it or we can say the subclass outside the package doesn’t have access to the protected method. It just has the method, through inheritance
Protected Access Control specifiers are not applied to class and interfaces. Method and member variables can be declared as protected access control specifiers, however using Interface method and member variables are not declared as protected access control specifiers.Protected Access control specifiers give the subclass give a chance to use helper method and variable
** Inheritance – “public class Father extends Grandfather” using extend keyword we are inheriting the property of grandfather in father class, which cannot be reference variable.
An Interesting example of protected access specifier:
We are going to create a public class Base in package pack1 with protected method
package pack1; public class Base { protected void display() { System.out.println("in Base"); } }
Now we are going to create another public class Derived in package pack2 and will discuss the complexity.
package pack2; import pack1.Base; public class Derived extends pack1.Base { public void show() { new Base().display();//Compilation Error } }
Now the question arises why this compilation error. Because new Base().display(); is not direct inheritance and a protected method can only be access by object of same package and since instance is being created in another package so Protected method can not be accessed.
Above code will work if we are going to call the method directly like this
package pack2; import pack1.Base; public class Derived extends Base { void show() { display();//No compilation error } }
Second way of using the protected method in Derived Class is to call the instance of Derived class to access the protected method of its Superclass Base. So here is the example
package pack2; import pack1.Base; public class Derived extends Base { void show() { new Derived().display();//No compilation error } }
Now lets move ahead with another example to see the protected access modifier.
Lets create there classes GrandFather in package pack1, Father class in pack2 package and Son class in package pack3 and please don’t add any code first just create empty classes with public access modifier.
package pack1; public class GrandFather { }
package pack2;
public class Father extends Grandfather {
}
package pack3;
public class Son extends Father{
}
Now add one protected method foo in GrandFather class like this
package pack1; public class GrandFather { protected void foo() { System.out.println("This is protected method in grandfather calss"); } }
So let see the three scenario in which this foo method could be called
Scenario 1: Accessing foo method by a class in same package pack1 lets say class name is SomeClass with instance of its subclass
package pack1; import pack2.Father; import pack3.Son; public class SomeClass { public void someMethod() throws Exception { Father f = new Father(); f.foo(); Son s = new Son(); s.foo(); } }
Here you will see no error and method can be accessed successfully.
Scenario 2: Accessing foo protected method using the same instance of subclass. Here again this method would be accessed successfully.
See the example
package pack2; import pack1.GrandFather; public class Father extends GrandFather{ public void fatherMethod() { this.foo(); } public void fatherMethod2() { Father f = new Father(); f.foo(); } }
In above example this keyword has been used to access the foo method that is protected in GrandFather class.
Same thing is also true with Son class see the example:
package pack3; import pack2.Father; public class Son extends Father{ public void sonMethod() { this.foo(); } }
Scenario 3: Access the protected method foo using GrandFather instance in subclass and this will throw exception since instance of GrandFather Class is not in same package. So see the example
Example 1: For Father Class
package pack2; import pack1.GrandFather; public class Father extends GrandFather{ public void fatherMethod() { GrandFather f = new GrandFather(); f.foo(); // compilation error GrandFather g = new Father(); g.foo(); // compilation error } }
For Son Class:
package pack3; import pack1.GrandFather; import pack2.Father; public class Son extends Father{ public void sonMethod() { GrandFather g = new GrandFather(); g.foo(); // compilation error GrandFather s = new Son(); s.foo(); // compilation error Father f = new Father(); f.foo(); // compilation error Father ff = new Son(); ff.foo(); // compilation error } }
Note:
Marking constructor as protected will be giving a compile time error & protected access gives the subclass a chance to use the helper method or variable, while preventing a non related class from trying to use it.
Private Access specifier: Private access specifier have limited access to class only where we can achieve encapsulation or hide unimportant data from the world. Method, variable & constructors that are declared private can be access within the same class only.
Class should not be declared as private, however we generally don’t apply private access specifier on class as well as constructor because that seems of not re-usability. In case of non-static method you can access directly because of this reference, even in below example of constructors but access using static method we have to create an object of the class
** Exception: Static method are not inherited in java, it will create a separate copy and static are related to class not the state of the object
Exception: Variables that are declared private can be accessed outside the class if public getter methods are present in the class. 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.
Lets create one class Example with few of its constructor as private.In this we will see that private constructor can be accessed in same class.
package pack1; public class Example { // public name; long time; private Example(long time) { this.time = time; } public Example(long time, long offset) { this(time); this.time = this.time + offset; } private Example() { // TODO Auto-generated constructor stub } public static Example ExampleNewTest() { // calling the constructor from // static method in same class return new Example(System.currentTimeMillis()); } public static void main(String[] args) { Example e = new Example(); // no compilation error Example e1 = new Example(5); //no compilation error since instance is being created in same class. } }
In above code, Both constructor are defined private but instance are created since both are in same class.
Lets create another class ExampleTest and lets see what happened
package pack1; public class ExampleTest { public static void main(String[] args) { Example e = new Example(); //Compliation error and error states to change visiblity to public } }
So it proves that private constructor can not be accessed out side the class.
Public Access Modifier: Public is accessible from anywhere and have widest scope from all the specifiers. 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.
Different Packages: However if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses. If the public class we are trying to access is in a different package, then the public class still need to be imported.
Thumb rules:
- Methods declared public in a superclass also must be public in all subclasses.
- Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
- Methods declared without access control (no modifier was used) can be declared more private in subclasses.
- Methods declared private are not inherited at all, so there is no rule for them.
Read Similar Posts
How to identify in Xpath with Contains give an example please