Working with access modifiers

Working with access modifiers


Posted in : Core Java Posted on : October 9, 2010 at 4:49 PM Comments : [ 0 ]

This section contains the detail about the access modifiers in java.

Working with access modifiers

Java has a number of access modifier to control access for classes, variables, methods and constructors. Following are the four types :

  • default - No need of access modifier, It is automatically visible to the package.

  • private - It is used to set the visibility to class level.

  • public - for setting visibility inside and outside package.

  • protected - for setting visibility to the package and all subclasses 

When a member of a class is modified by the public specifier, then that  member can be accessed by any other code. When a member of a class is specified as private , then that member can only be accessed by other members of it's class. Now you can understand why main() has always been preceded by the public specifier. It is called by code that is outside the program- i.e., by the Java run time system. When no access specifier is used , then by default the member of a class is public within its own package.

Example :

Given below program demonstrates the difference between public and private :


class TestDemo {
	int a;// default access
	public int b;// public access
	private int c;// private access

	// methods to access c
	void setc(int i) { // set c's value
		c = i;
	}

	int getc() { // get c's value
		return c;

	}
}

public class AccessDemo {
	public static void main(String args[]) {
		TestDemo ob = new TestDemo();

		// These are OK, a and b may be accessed directly
		ob.a = 10;
		ob.b = 20;

		// This is not OK and will cause an error
		ob.c = 100;// error

		// you must access c through its methods
		ob.setc(100); // Ok
		System.out.println("a,b, and c :" + ob.a + "" + ob.b + "" + ob.getc());
	}

}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac AccessDemo .java
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The field TestDemo.c is not visible

This code will not compile because c is declared as private and it was tried to access outside the class that's why it gives compilation error.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics