• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

protected access from another package

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Following class Base1 is in package base1p
package base1p;
public class Base1{
protected void amethod()
{
System.out.println("amethod1");
}
}

Following class Base2 is in default package.
import base1p.Base1;
public class Base2 extends base1p.Base1
{
public static void main(String argv[])
{
Base1 b = new Base1();
b.amethod();
}
}
This gives a compiler error saying "Can't access protected method amethod in class base1p.Base1. base1p.Base1 is not a subclass of the current class. b.amethod();"
But if both classes are given in the same source file, it prints "amethod1".
Any idea why it gives this error as protected should be accessible from another package?.
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The explanation can be found in
The Java Language Specification, Section 6.6.2, Details on protected Access.


Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then:
...
If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.


If you change the following statement
Base1 b = new Base1();
to
Base2 b = new Base2();
then it should work.
I haven't tried it myself, so please post your results if you try it.
 
biju joseph
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Dan.
You are correct, it works with code
Base2 b = new Base2();
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic