BIG
DATA

JAVA

ACCESS MODIFIERS IN JAVA

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

The access modifiers in java specifies accessibility or scope of a data member, method, constructor or class. A Java access modifier specifies which classes can access a given class and its fields, constructors and methods. Access modifiers can be specified separately for a class, its constructors, fields and methods. Access level modifiers determine whether other classes can use a particular field or invoke a particular method. In a way Java access modifiers help structure your program to have proper scoping. There are 4 types of java access modifiers:

  • private
  • default or package-private (no explicit modifier)
  • protected
  • public

private access modifier

The private access modifier is accessible only within class. Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. Code inside subclasses cannot access the variable or method, nor can code from any external class.
Private access modifier is the most restrictive access level.
Classes and Interfaces cannot be private. If a class or interface is marked as private then no external class can access the class or interface. This doesn't really make sense for classes though. Therefore, the access modifier private is mostly used for fields, constructors and methods.

class A{  
	private int data = 10;  
	private void displayData(){
		System.out.println("Data:=" + data);	//can be accessed within class
	} 
}  
  
public class Demo{  
	public static void main(String args[]){  
		A obj = new A();  
		System.out.println(obj.data);	//Compile Time Error  
		obj.display();	//Compile Time Error  
	}  
}  

In the above example, I have created 2 classes 'A' and 'Demo'. 'A' class contains private data member and private method. In class 'A', 'displayData' method can access 'data' variable but when Demo clas is trying to access We will get compile time error because we are accessing these private members from outside the class.

[Note]: Class cannot be private or protected except nested class.

default access modifier

If you don't use any modifier, it is treated as default modifier. The default modifier is accessible only within package. Default access levels means that code inside the class itself plus code inside classes in the same package as this class. It is also called as package-private or no explicit modifier or package access modifier.

Subclasses cannot access methods and member variables in the superclass, if they have default accessibility declared, unless the subclass is located in the same package as the superclass.

public class A {
    int data = 10;
}

public class B {
    A obj = new A();

    public int getData{
        return obj.data;
    }
}

The 'B' class above can read the 'data' member variable of A's object, provided that 'A' and 'B' are located in the same package.

[Note]: packages are named groups of related classes

protected access modifier

The protected access modifier is accessible within package and outside the package but through inheritance only. That is accessible by all the child classes and also by all the classes within the same package.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class

public class A {
    protected int data = 10;
}

public class B {
    A obj = new A();

    public int getData{
        return obj.data;
    }
}

The 'B' class above can read the 'data' member variable of A's object, provided that 'A' and 'B' are located in the same package. But lets have class 'C' which is not in the same package nor a child class of 'A'.

public class C {
    A obj = new A();

    public int getData{
        return obj.data;	//compile time error
    }
}

The 'C' class cannot access data variable of A's object since it is beyond the scope.

public access modifier

The public access modifier is accessible everywhere. No restriction modifier.

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 world.

However if the public class we are trying to access is in a different package, then that public class needs to be imported.

public class A {
    public int data = 10;
}

public class B {
    A obj = new A();

    public int getData{
        return obj.data;
    }
}

The 'B' class can access the data field in 'A' no matter what package the 'B' is located in, because both the class are declared public.

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Access Modifiers for Class

Classes in java can have only public and default access modifiers. Access modifier assigned to a Java class takes precedence over any access modifiers assigned to fields, constructors and methods of that class.

Public

When set to public, the given class will be accessible to all the classes available in Java world.

Default

When set to default, the given class will be accessible to the classes which are defined in the same package and no other class outside the same Java package can access that class, including its constructors, fields and methods. It doesn't help even if you declare these fields public, or even public static.

Note:private and protected access modifiers cannot be assigned to a class.
Example,

private class Car {
	
}

If you mark class as private like above, following error will be shown:

accessmodifier

Access Modifiers for Interfaces

Like in classes, you cannot use the private and protected access modifiers in interfaces either because Java interfaces are meant to specify fields and methods that are publicly available in classes. Also the fields and methods in interfaces cannot be marked as default access modifier (no access modifier) because fields and methods in interfaces are implicitly declared public if you leave out an access modifier.

Access Modifiers for Methods

All the 4 Java modifiers are applicable to methods.

Default

When a method is marked to default it will be accessible to the class which are defined in the same package. Any method in any class within the same package can access the given method.

Public

When a method is marked to public it will be accessible from any class available in the Java world depending on class level access.

Protected

If a method is marked as protected, it will be accessible within the class and from its child classes defined in the same or different package.

Private

If a method is defined as private, it will be accessible only within the class it is defined and not even its subclass(child class).

Access Modifiers for Variables

  • Instance / Static Variable

    All the 4 Java modifiers are applicable to Instance / Static Variables.

    Default

    If a variable is set to default, it will be accessible to the class where variable is defined and also the classes which are defined in the same package via Inheritance or Direct access.

    Public

    When a variable is marked to public it will be accessible from any class available depending on class level access.

    Protected

    If a variable is marked as protected inside a class, it will be accessible within the class and from its child classes defined in the same or different package.

    Private

    If a variable is defined as private, it will be accessible only within the class it is defined and not even its subclass(child class).

    Note:As said before access modifier assigned to a Java class takes precedence over any access modifiers assigned to fields, constructors and methods of that class. Therefore if the class is visible only then the variables defined inside that class will be visible . If the class is not visible then no variable will be accessible, even if it is set to public.

  • Local Variable

    Local variables cannot be marked with any of the Access Modifiers. Only final can be applied to a local variable.

    void myCar(){
    	public int speed=10;
    	.....
    	//some more java statements
    }
    
    accessmodifier

Access Modifiers and Inheritance

A fundamental principle in OOP says that the child class is a fully-fledged instance of the parent class, and must therefore present at least the same interface as the parent class.

Hence when you create a childclass of some class, the methods in the childclass cannot have less accessible access modifiers assigned to them than they had in the parent class. While it is not allowed to decrease the visibility of an overridden method, it is allowed to increase visibility. For example, if a method in the parent class is public then it must be public in the child class too. If a method in the parent class is protected then it must be either protected or public in the childclass.

class Vehicle {
    public void speed() {}
}

class Car extends Vehicle {
    private void speed() {}
}

Car mycar = new Car();
Vehicle vh = mycar;
mycar.speed();  // Can't do it! compilation error
vh.speed();  // Works fine!

If you mark a method in child class with less accessibility than that in the parent class, like in above for speed method, following compilation error will be shown.

accessmodifier

The following are the guidelines to implement inherited methods:

  • Methods marked public in a parent class, also must be public in all childclasses.
  • Methods declared protected in a parent class must either be protected or public in child classes and no, they cannot be marked as private.
  • Methods declared without access control (no modifier) can be declared without access control in child classes too or can be decalred as protected or public also.
  • Methods marked private cannot be inherited at all, hence there are no guidelines for them.

Direct Access vs Inheritance

public class CoreJavaGuru {

	public static void main(String [] args) 
	{
		Car sc = new Car();
		sc.printSpeed();
	} 
}

class Vehicle {
	protected int speed=80;
}

class Car extends Vehicle {
	void printSpeed() {
		//Access speed variable through inheritance
		System.out.println("Speed through Inheritance:" + speed);  

		//Access speed variable through Direct access
		Vehicle vh = new Vehicle();
		System.out.println("Speed through Direct access:" + vh.speed);
	}
}

Output,

Speed through Inheritance:80
Speed through Direct access:80