• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected keyword

 
rupika deval
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 50175
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic