jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes protected keyword Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "protected keyword" Watch "protected keyword" New topic
Author

protected keyword

rupika deval
Greenhorn

Joined: Jan 04, 2008
Posts: 6
[code]
package p1;

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: 26
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: 39478
    
  28
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: 26
Originally posted by Campbell Ritchie:
. . . and to other classes in the same package.


Oh yess...

Thanks for the addition...

Kind Regards,
Suraj
[ March 12, 2008: Message edited by: Suraj Berwal ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: protected keyword