WHAT IS THE LAW BEHIND THE protected
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   sanju_thomas
Posted On:   Monday, December 20, 2004 10:36 AM

package aa; public class A { protected int x; } package bb; import aa.*; public class B extends A { public void test() { x=100; } } package cc; import bb.*; class C extends B { public void test1() { x=1000; } } is this x available in the class C ??? It is !, Then what is the RULE behind this protected ??? can any one crack this ??? with regards    More>>


package aa;


public class A

{

protected int x;

}



package bb;


import aa.*;


public class B extends A

{

public void test()

{
x=100;

}

}



package cc;


import bb.*;


class C extends B

{

public void test1()

{

x=1000;

}

}




is this x available in the class C ???



It is !, Then what is the RULE behind this protected ???


can any one crack this ???


with regards

sanju

   <<Less

Re: WHAT IS THE LAW BEHIND THE protected

Posted By:   Chandra_Patni  
Posted On:   Monday, December 27, 2004 05:14 PM

Subclasses and package private classes can access any of the protected variable. The variable are said to hide. So, you can call any of the x you wish. That's certainly not true for the methods. See the following example. Also, Java Online Tutorial has a very good example of protected.


package aa;
public class A {
protected String s = "A";
public void test() {
System.out.println("A.test()");
}
}

package bb;
public class B extends A {
protected String s = "A";
public void test() {
System.out.println("B.test()");
}
}

package cc;
public class C extends B {
protected String s = "A";
public void test() {
System.out.println("C.test()");
System.out.println("x is "+ s); //same as super.s
System.out.println("x is "+ ((A) this).s); //can access A.s
super.test();
//but we can only call B.test() method. There is no way to call A.test()
}

public static void main(String[] args) {
C c = new C();
B b = c;
A a = c;

System.out.println("x is "+ c.s); //same as super.s
System.out.println("x is "+ ((A) c).s); //can access A.s
System.out.println("x is "+ ((B) c).s); //can access B.s
a.test(); //will call c.test()
b.test(); //will call c.test()
c.test(); //will call c.test()
}
}

Re: WHAT IS THE LAW BEHIND THE protected

Posted By:   WarnerJan_Veldhuis  
Posted On:   Tuesday, December 21, 2004 05:44 AM

Protected means that the field is visible ONLY to classes in the SAME package AND visible to classes that EXTEND the class containing the protected variable



@see: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
About | Sitemap | Contact