• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

JQ+ question from Declaration and Access Control

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The question reads as follows:
Consider following two classes:
//in file A.java
package p1;
public class A
{
protected int i = 10;
public int getI() { return i; }
}
//in file B.java
package p2;
import p1.*;
public class B extends p1.A
{
public void process(A a)
{
a.i = a.i*2;
}
public static void main(String[] args)
{
A a = new B();
B b = new B();
b.process(a);
System.out.println( a.getI() );
}
}
What will be the output of compiling and running class B ?
I am simply not able to understand the output.
Can anyone shed some light for me please. The explanation is not very clear to me.
Thanks
Rahul
The explanation given is :
Although, class B extends class A and 'i' is a protected member of A, B still cannot access i , (now this is imp) THROUGH A's reference because B is not involved in the implementation of A.
Had the process() method been defined as process(B b); b.i would have been accessible as B is involved in the implementation of B.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answer can be found in the JLS. Also see example 6.6.7.
Basically I think because i is a protected member of A, and B extends A,
B can access i if:

  • It does so without going through another reference (i=i*2)
  • Or it does so using a B reference.

  • In your example, B is accessing i through an A reference (a.i=a.i*2) which isn't allowed.
    - Dave
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic