This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
public class AccessModifiers{ int n_pack =1; private int n_pri = 2; protected int n_pro = 3; public int n_pub = 4;
public AccessModifiers(){ System.out.println("Base Constructor"); System.out.println(" n_package = "+n_pack); System.out.println("n_private = "+n_pri); System.out.println("n_protected = "+n_pro); System.out.println("n_public = "+n_pub); } public static void main(String[] args){ AccessModifiers am = new AccessModifiers(); }
}
package p2;
import p1.AccessModifiers;
class AccessModifiers03 extends AccessModifiers { public static void main(String args[]){ AccessModifiers am = new AccessModifiers(); //System.out.println(" n_package = "+n_pack); //System.out.println("n_private = "+n_pri); System.out.println("n_protected = "+n_pro); System.out.println("n_public = "+am.n_pub);
}
} [\code] i am getting error while printing n_pro even if it is declared as protected, please can you help me...
Suraj Berwal
Greenhorn
Joined: Dec 28, 2001
Posts: 25
posted
0
The protected keyword means that the variable defined in super class will also be visible in the objects of subclass.
In your case there is a Static reference to the Non-Static variable "n_pro".
This will cause the compiler to throw an error. Also to print it in subclass you have to instantiate an object of subclass and call it in the format obj.variable.
See the modified code below for subclass:
Hope this helps
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32644
4
posted
0
Originally posted by Suraj Berwal: The protected keyword means that the variable defined in super class will also be visible in the objects of subclass.
. . . and to other classes in the same package.
Suraj Berwal
Greenhorn
Joined: Dec 28, 2001
Posts: 25
posted
0
Originally posted by Campbell Ritchie: . . . and to other classes in the same package.