Access Variable from other class in same 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 to access variables with different access modifiers from other class in same package

package com.accessmodifier;

/*
 * Here we will learn to access variables with different access modifiers from other class in same package 
 */
public class AccessVariableFromAnotherClass {

	// We will try to access below variable from other class
	public int i;
	private int j;
	protected int k;
	int l;
}

class AnotherClass {
	// Here we will access variable of above class with different AM
	public static void main(String args[]) {
		AccessVariableFromAnotherClass class1 = new AccessVariableFromAnotherClass();

		/*
		 * Variables with different access modifiers can be accessed except
		 * Private variable as it is not visible outside class. Hence Line 25
		 * will have compile time error
		 * "The field AccessVariableFromAnotherClass.j is not visible"
		 */
		System.out.println("Value of public variable" + class1.i);
		System.out.println("Value of private variable" + class1.j);
		System.out.println("Value of protected variable" + class1.k);
		System.out.println("Value of Default variable" + class1.l);
	}
}

 

Trackback from your site.

Comments (1)

Leave a comment

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