Sunday, February 22, 2015

Packages

Package it is used to store your classes, avoid class name conflict and with the help of access specifier we can control the access.
we have 4 access modifier public, protected, private and no access specifier mentioned.

--public is accessed inside the class,inside the package,outside the class,outside the package and even in subclass and non subclass.
--private is accessible only inside the same class and other all places it is restricted.
--no access specifier it is accessible from the same class, subclass non subclass from the same package but not outside the package.
--protected is accessible in same class , subclass, non subclass of the same package other package subclass but not the other package non subclass.
Follow the below example with the comments


protectedclass.java
package p1;

public class protectedclass {
	
	int i =10;
	private int privatev=100;
	protected int protectedv=1000;
	public int publicv=10000;

}

subclass.java

package p1;

public class subclass extends p1.protectedclass {
		
		subclass(){
			System.out.println("access default variable "+i);
			//System.out.println("access to private variable "+privatev);//private cannot be accessed outside the class
			System.out.println("access to protected variable "+protectedv);
			System.out.println("acces to public variable "+publicv);
		}
}

nonsubclass.java

package p1;

public class nonsubclass {
	nonsubclass(){
		protectedclass p=new protectedclass();
		System.out.println("access default variable "+p.i);
		//System.out.println("access to private variable "+p.privatev);//private cannot be accessed outside the class
		System.out.println("access to protected variable "+p.protectedv);
		System.out.println("acces to public variable "+p.publicv);
	}
}

Different package p2 protectedclass.java

package p2;

public class protectedclass extends p1.protectedclass{
	protectedclass(){
	
	//System.out.println("access default variable "+i);default access in not valid outside the package
	//System.out.println("access to private variable "+privatev);//private cannot be accessed outside the class
	System.out.println("access to protected variable "+protectedv);
	System.out.println("acces to public variable "+publicv);
	}

}

nonsubclass.java
package p2;

public class nonsubclass {
	
	nonsubclass(){
		p1.protectedclass p2=new p1.protectedclass();
		
		//System.out.println("access default variable "+p2.i);//does not work in different package
		//System.out.println("access to private variable "+privatev);//private cannot be accessed outside the class
		//System.out.println("access to protected variable "+p2.protectedv);//proctected does not work in non subclasses
		System.out.println("acces to public variable "+p2.publicv);
	}

}

>>>Final
------------------------------------------------------------------------------------------------------------