Access Modifiers in Java

This tutorials explains the various access modifiers used in Java language and the scope for the each modifier. There is four types of access modifiers in Java.

  • private
  • default
  • protected
  • public

Private Modifier

If you declare anything private inside a class, then it must be accessed inside that class. Other classes can not access that variables or methods directly.

  • We can not declare a class as private
  • Variables and methods can be declared as private.
  • If you declare a constructor as private, we can not create instance using that constructor.
  • Private is the least access modifier.
package javabeat.net.core;

public class SuperClass {
	private int i;
	private SuperClass(){
		//Private constructor
	}
	private void method(){
		//Private method
	}
}

Default Modifier

If you don’t declare access modifier, then it is considered as the default access. It means that the access is granted within the same package.

  • Default access has no keyword. Without any access modifier is considered as default access.
  • This access is applicable for classes, methods and variables.
package javabeat.net.core;

public class SuperClass {
	int i;
	SuperClass(){
		//Default constructor
	}
	void method(){
		//Default method
	}
}
package javabeat.net.core;

public class OtherClass {
	void method(){
		SuperClass class1 = new SuperClass();
		System.out.println(class1.i);
	}
}

Protected Modifier

If you declare a method or variable as the protected, it can be accessed within the same package and sub classes in the other packages.

  • Classes can not be declared as protected access.
  • Variables and methods can be declared as protected.
  • The main purpose of the protected is to give access for its sub classes.
package javabeat.net.core;

public class SuperClass {
	protected int i;
	protected SuperClass(){
		//protected constructor
	}
	protected void method(){
		//protected method
	}
}

package javabeat.net.core;

public class SubClass extends SuperClass{
	protected void method (){
		SuperClass class1 = new SuperClass();
		System.out.println(class1.i);
	}
}

Public Modifier

If you declare as public, then the data member can be accessed from anywhere .

  • Classes, variables and methods can be public.
  • It is the maximum access level

Summary of Access Level

ModifierInside ClassInside PackageOther Package by Subclass OnlyOther Package
PrivateYNNN
DefaultYYNN
ProtectedYYYN
PublicYYYY

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*