Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on apckage

 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Luciano Queiroz
Ranch Hand
Posts: 172
  • 0
  • Mark post as helpful
  • send pies
  • 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".
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic