Access Modifiers in java
The access modifiers in Java specifies accessibility or scope of a data member, method, constructor or class.
There are 4 types of Java access modifiers:
- private
- default
- protected
- public
Private Access modifier:
– private keyword can be applied to fields, methods and inner class in Java.
– 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.
– Private helps to encapsulate your methods and variables most effectively. What do I mean by encapsulate? I mean that only things that should be able to access those methods and variables can do so.
Why can’t we declare class and interface as private?
The answer is: We can declare class as private. Only top level class can’t be private. This is because if you declare top level class as private it wont be accessible by anyone. So having such class is useless.
Why should you make your members private ?
As I said earlier keeping member variable or method private as default provides Encapsulation. Don’t make any method by default public which most of Java programmers do, that’s against concept of encapsulation in Java.
Benefits of making variables or methods private in Java
– private methods are well encapsulated in class and developer knows that they are not used anywhere else in code which gives them confident to change, modify or enhance private method without any side-effect.
– IDE like Netbeans and Eclipse use this information and automatically check whether private methods are used inside Class or not and can display relevant warning to improve code quality or delete unused statements, variables or methods.
– private methods use static binding in Java and they are bonded during compile time which is fast compared to dynamic binding which occurs during runtime and also gives chance to JVM to either inline the method or optimize it.
– Private method can not be overridden in Java, not even inside inner classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Public class A { Private int message; Public void callPrivate() { System.out.println(“Not a private”); privateMethod(); } private void privateMethod () { System.out.println(“inide private method”) } } class B { A obj=new A() Obj.callPrivate() Obj.privateMethod()//can’t call private method outside class. String msg=Obj.message //can’t access private fields outside class } |
Can a Java subclass declare a private method available in its superclass ?
The answer is yes. But reverse is not possible i.e if method is declared as public, you can’t declare it as private in subclass. You can’t restrict access level of method in subclass. Since private member variable ar visible only within class level, you can have same member variables in sub class. This is why private methods can’t be overridden. Look at the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class SuperClass { private void privateDemo() { System.out.println("super class"); } } class SubClass extends SuperClass { protected void privateDemo() { System.out.println("Sub class"); } } public class privateMembersExample { public static void main(String args[]) { SubClass sL = new SubClass(); sL.privateDemo(); } } |
The output is: sub class.
Private constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:
1 2 3 4 5 6 7 8 9 |
class A{ private A(){}//private constructor void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A();//Compile Time Error } } |
Public access modifier:
– The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
– A class, method, constructor, interface etc. declared public can be accessed from any other class. However if the public class we are trying to access is in a different package, then the public class still need to be imported
– In class inheritance, all public methods and variables of a class are inherited by its subclasses.
– 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.
– This is useful for when the variable should be accessible by your entire application. Usually common routines and variables that need to be shared everywhere are declared public.
– Java’s public access modifier is the least protective of the modifiers, and should be used only when you absolutely know that you want anything and everything to be allowed access to the methods and variables.
Protected access modifier
– 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. Because the reason is same as explained for private.
– Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
– Let’s say we define a protected method in A class called methodA(). Now, we can use it in the B class if B is a subclass of A (using extends). Also notice that a AB is NOT a subclass of Animal and therefore has no access to the method. The below picture illustrates this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class A { protected void methodA() { //definition } } class B extends A { public void methodB() { //definition } } class AB { public void methodAB() { B objB=new B(); objB.mathodA();//error } } |
In the above code, you will see that A has a protected methodA() method, and B, since it’s a subclass, can call that method. AB on the other hand is not a subclass and is also not in the same package as Animal, so it has no access to methodA() .
Default Access modifier
What happens if you do not put any of the Java access modifiers on your methods and variables?
– Java still compiles your code. No access modifier means that the method or variable defaults to package protected. You get all of the same access as protected minus the ability for subclasses in other package to access the method or variables.
The default modifier is not used for fields and methods within an interface.
Below is a program to demonstrate the use of public, private, protected and default access modifiers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
class BaseClass { public int x = 10; private int y = 10; protected int z = 10; int a = 10; //Implicit Default Access Modifier public int getX() { return x; } public void setX(int x) { this.x = x; } private int getY() { return y; } private void setY(int y) { this.y = y; } protected int getZ() { return z; } protected void setZ(int z) { this.z = z; } int getA() { return a; } void setA(int a) { this.a = a; } } public class SubclassInSamePackage extends BaseClass { public static void main(String args[]) { BaseClass rr = new BaseClass(); rr.z = 0; SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(20); System.out.println("Value of x is : " + subClassObj.x); System.out.println("Value of y is : "+subClassObj.y);//y is private subClassObj.setY(20);//can't access because setY is private //Access Modifiers - Protected System.out.println("Value of z is : " + subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : " + subClassObj.z); //Access Modifiers - Default System.out.println("Value of x is : " + subClassObj.a); subClassObj.setA(20); System.out.println("Value of x is : " + subClassObj.a); } } |
Java is being able to handle different levels of access modifiers so that your code is a lot more readable and maintainable. It also helps to reinforce a programmer’s wishes as to what can and what cannot be done.
Leave a Reply