How to Access Class from outside package

Written by admin on . Posted in Learn By Example

4 Flares Twitter 0 Facebook 2 Google+ 2 Email -- Email to a friend 4 Flares ×

Here we will learn how to access Class with different AM(Public / Default) from different package

package com.accessmodifier;

/*
 * Here we will learn how to access Class with different AM(Public / Default) from different package
 */
public class AccessClassDifferentPackage {

}

class AnotherClass{

}

Class in different package

package com.accessmodifier2;

import com.accessmodifier.AccessClassDifferentPackage;

/*
 * If you try to import default/non public class compiler will give error
 * "The type com.accessmodifier.AnotherClass is not visible"
 */
import com.accessmodifier.AnotherClass;

/*
 * Here we will try to access Classes with different access modifiers.
 * Note*: This class is in different package. See Above
 */
public class AccessClassFromHere {

	public static void main(String args[])
	{
		//Public class can be accessed without any problem
		AccessClassDifferentPackage class1 = new 	AccessClassDifferentPackage();

		/*
		 * Default class can not be accessed from here as it is not visible.
		 * Compiler will give error "AnotherClass cannot be resolved to a type"
		 */
		AnotherClass class2= new AnotherClass();

		/*
		 * Even importing the class will not make any difference. See Above
		 */
	}
}

 

Trackback from your site.

Leave a comment

4 Flares Twitter 0 Facebook 2 Google+ 2 Email -- Email to a friend 4 Flares ×