• 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

Question on apckage

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
package p1;
public class A {
protected int i = 10;
public int getI() { return i; }
}

package p2;
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() );
}
}


Giving error on i . Please explain
My own cde
 
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's clear!

First of all, you must write:

import p1.A;


Second, you can not access i through A.
You must access i only by inheritance, that is, you must type i directly inside class B.

Ex.:


package p2;

import p1.A;

public class B extends p1.A
{
public void process(A a)
{
i = i*2;
}

public static void main(String[] args)
{
A a = new B();
B b = new B();
b.process(a);
System.out.println( a.getI() );
}
}


But in this case, the output will be "10".
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You mean: This gives a compile error in the method process(A a) in class B.

This is one of the peculiarities of how 'protected' works. When a field is 'protected', it is visible in subclasses and in classes of the same package; but only the field of the object itself is visible. In this example, you are looking at field 'i' of a different object - and then it's not visible.

Section 6.6.2 of The Java Language Specification explains this (with just a very short sentence):

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.



Note: Please use code tags when you post source code.
 
Message for you sir! I think it is a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic