Regarding Protected access specifier

Hi ,
I thought that indeed you could access protected data member from another package IF you are using Inheritance. It makes the data memeber in question "friendly" to the derived class. At least that is my understanding.
You can not access protected data element directly in different packages. package test1;
public class Test123 {
protected int x=42;
package test2;
import test1.Test123;
public class Test234 extends test1.Test123{
     public static void main(String args[]){
          Test123 ob=new Test123();
          System.out.println("x="+ob.x);
but My question is that ..if u run this program its not compile..Compile time exception is throws saying that the field Test123.x is not visible..but according to protected access specifier this will work...and one thing that if i make field ' x ' of Test123 as public it is working... How it is possible ...can anybody pls help it out.. Thanx in advance...

This access is provided even to subclasses that reside in a different package from
the class that owns the protected feature.As you have found this (and similar) can be confusing.
Have a look at the Java Language Specification (http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.7) "6.6.7 Example: protected Fields, Methods, and Constructors". Can you see the difference between the delta() and delta3d() methods?
"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." As another example of this, the following compiles OKpackage test2;
import test1.Test123;
public class Test234 extends test1.Test123 {
    public static void main(String args[]) {
        Test234 ob = new Test234();
        System.out.println("x=" + ob.x);
}When run it prints "42" - showing that the same d@mn field is being accessed! Like you, I'd appreciate hearing a simple rationale for this (if there is one).

Similar Messages

  • Comparing access specifiers  Protected

    Why protected access specifiers are used ? .
    Where comes the difference of using
    void fun1(int a,intb)
    and
    protected void fun(int a, int b)
    }

    From http://www.rijas.t35.com ,
    Note that I did experiment in a variable as protected
    not in a method
    I did both but saw no diffrence from
    no-access Specifiers and
    protected access specifiers
    I extend it two times and
    used package one time
    but saw no difference .
    I am sure ...U can help me !!!
    package pkg;
       class DatePro
           protected  int yy;
       class DatePro2 extends DatePro
           protected int mm;
    public class Date extends DatePro2
                   int dd;
              public void getDate()
                        System.out.println(dd+" "+mm+" "+yy);
           public  void setDate(int d,int m, int y)
                        dd=d;
                        mm=m;
                        yy=y;
    import pkg.*;
    class PkgCheck1
             void   pkgCall()
                        int a=100,b=200;
                        Date d1=new Date();
                        d1.setDate(10,5,07);
                        d1.getDate();
    class PkgCheck2 extends PkgCheck1
                 public static void main(String args[])
                    PkgCheck2 p1 =new PkgCheck2();
                   p1.pkgCall();
                    System.out.println("Hi  I am Rijas P A "+ " You  create a folder pkg  and place Date.java in it");
                    System.out.println("Place PkgCheck2.java - above that folder compile and run PkgCheck2.java");
    thank you...
    Edited by: omnie on Oct 26, 2007 4:27 PM

  • Access specifiers for interface methods

    When we implement the interface ,we have to specify the implementing method access specifier to be "PUBLIC" ,but not "PROTECTED" or "PRIVATE".
    Compiler is giving an error -- attempting to assign weaker access privileges ,when we specify protected.
    what is the internal reason for this?Why we shouldnt make the access weaker in the implementing class.
    Can any one help me on this.Your help is highly appreciated.

    When we implement the interface ,we have to specify
    the implementing method access specifier to be
    "PUBLIC" ,but not "PROTECTED" or "PRIVATE".
    Compiler is giving an error -- attempting to assign
    weaker access privileges ,when we specify protected.
    what is the internal reason for this?There is absolutely no point in having a private interface method. The interface represents a visible abstraction and private methods are never visible so it is a contradiction in terms.
    An interface is intended to represent an abstraction that a user (software) uses. Protected via child/parent represents a usage that is restricted to a child from a parent. The child can already see the parent so there is no point in having an abstraction for the child. And it would probably be unwise to limit a child by such an abstraction.
    Protected via the package and interfaces is more contentious as to why it is not allowed. There are those that argue that this should be allowed so that a package can use interfaces but restrict them to the package. To me this seems like a minor point given that most interfaces will probably represent an abstraction to other packages and not within a single package. This applies specifically to default access as well.

  • Access Specifiers for a class

    Why we can't declare private or protected for a class as access specifier.
    Can you give me an example on it.

    This is the third time someone asked something like this today:
    http://forum.java.sun.com/thread.jspa?threadID=664848 (where someone references your post on JavaRanch).
    http://forum.java.sun.com/thread.jspa?threadID=664790

  • Need new access specifier

    I think there must be another access specifier that is like protected but not friendly, I mean only the supclasses can access that, not the classes in that package.
    Suppose a class that has private or friendly fields and I had to define another field of the same type for its subclass.
    Or I have a class with a protected field that I know I will use it if I want to define a subclass of it. But I don't want to let the other classes in thatpackage modify this field unintentionally.
    The problem is not only for fields. There are situations that I want to permit subclasses to call a method but I don't want other classes in the same package call it.

    there isn't.
    perhaps you need to think more about which classes sit in which packages ?
    maybe a better package structure would give you this control.

  • About access specifiers (inheritance)

    abstract Class A
    abstract public add();
    Class B extends A
    protected add() //this wont work
    //some code here
    The access specifier for add method in A is public ,and in B is protected.This is not allowed by compiler.
    Why cant we make the access weaker in the sub class?What is the drawback in allowing to make the access weaker.

    Because any class that uses class A has the right to expect to use the add() method, since it is public in A. Since B is an A, it must allow some one to use an instance of B as if it were an A.

  • C++: access-specifiers

    I'm currently taking a course in C++ programming and we are covering classes and objects. We had a discussion last night and could not come up with a good example of why you would ever need to use specifically, the private access-specifier, along with protected. Would this ever be useful and why? Please give an example.

    Presumably, as a very trivial example, you might not
    want a very particular error announcement to be
    accessible outside the actual class that it concerns.
    Start doing that kind of thing and who knows where
    you'll end up; you might get the kind of Error
    Messages of Dubious Provenance™ emitted by The
    Flagship Product™ of That Big Famous Software
    Company™. I mean, if the subclass is going to take on
    responsibility for detecting and reporting problems
    with its parent, think of all the other b.s. it's
    going to have to keep track of as well. You might as
    well just write straight C code.
    But along with the free advice, you get this bit of
    nagging: It's really unfair to yourself and your
    mates in the discussion group not to explore
    open-ended questions like this on your own. Even
    coming up with an off-target answer after thinking
    about it for awhile is better than having an answer
    handed to you. In the present context, Please give
    an example sounds suspiciously like asking for
    help with homework. Doing that online is VERY poor
    form.
    Mr.Stein,
    Your quick response is appreciated but the online scolding is not. This discussion was trivial and had nothing to do with an actual assignment. The instructor as well as my mates could not think of a reason why this would be done. Exploring this open ended question on my own would not only take time I don't have but also produce VERY poor design considering you should know what your code is doing before you sit down to type. I consider this forum a resource available for things such as this. I'm sure google could have pulled up actual code but I wanted interaction with coders such as yourself. Once again, your response is appreciated.

  • What is the difference between access specifiers and access modifiers?

    what is the difference between access specifiers and access modifiers? are they same? if not what is the difference.

    Access Specifier are used to specifiy how the member variable ,methods or class to other classes.They are public ,private and protected.
    Access Modifier:
    1.Access
    2.Non Access
    Access:
    public ,private,protected and default.
    Non Access:
    abstract,final,native,static,synchronized,transient,volatile and strictfp

  • I'm confused about protected access - any insight ?

    I'm trying to understand how the protected access modifier works. I have tried to compile some example code and I'm seeing behavior which appears to go against what the text I'm using claims should happen. To wit:
    My understanding is that any subclass and any class in the same package has access to the protected member of a class. Default access (when no access modifier is used at all) allows access only to classes in the same package.
    I have the following two classes:
    //--------  Parent.java ---------------
    package testpkg.p1;
    public class Parent
        public int x = 7;
        protected int getXValue ()
            return x;
    //--------- Child.java --------------
    package testpkg.p2;
    import testpkg.p1.Parent;
    public class Child
        extends Parent
        public static void main (String[] args)
            Child child = new Child();
            System.out.println("Child X: " + child.getXValue() + "\n");
            System.out.println("Parent X: " + child.testParent());
        public int testParent ()
            Parent parent = new Parent();
            return parent.getXValue();
    }I get the following compilation error:
    $ javac -d ../lib Parent.java Child.java
    Child.java:18: getXValue() has protected access in testpkg.p1.Parent
    return parent.getXValue();
    ^
    1 error
    Now it seems to me that everything should compile fine since the Child class is a subclass of the Parent class, and as such should have access to the protected member method getXValue(). However this obviously isn't the case. It seems that the behavior is more like what is described for default access, i.e. no access by any class outside of the package, no matter if it is a subclass or not.
    Can anyone enlighten me on this ? Am I missing something obvious ?
    Thanks in advance for any feedback.
    -James

    You know that you don't have to use the "protected"
    modifier.Yes you do.
    In fact, when I learned Java, it was called
    "package" scope, not protected. But the same
    principle applies.No, the principles outlined above and in the Java Language Spec apply.
    "protected" or "package" means that only classes
    within the package itself can have access. You do not
    actually have to place any modifier at all since this
    is the default scope.No, protected adds the ability to access ex-package super class members from a child class instance. Try compiling the above example without specifying protected access.
    Pete

  • Undeletable protected access points HELP!

    Hi,the problem is when I open destinations in my N8 there are 106 access points there all called 'boingo',and i can't delete any of them.When I try to delete it says unable to delete protected access point.I've tried updating software and also making 'factory settings' but nothing changes.That *hits are always there !!!
    Solved!
    Go to Solution.

    Thanks mate., even it has been 4 years since I posted this question. I came back here because Microsoft sent me an e-mail regarding the merging of Nokia Discussions account to my Microsoft Account. Good old days. RIP Nokia.

  • Problems with protected access in java.util.vector

    Hi,
    basically i'm trying to use the method removeRange(int,int) of class Vector from the java API.
    I keep getting the following compiler message:
    removeRange(int,int) has protected access in java.util.vector.
    This seems rather vague, and i don't know quite what to do?
    Thanks in advance

    removeRange(int,int) has protected access in java.util.vector.
    This seems rather vague, and i don't know quite what to do?As error messages go, that's pretty clear: method removeRange is a protected method and you can only call public ones of Vector, right? You can always combine subList and clear:
    vec.subList(fromIndex, toIndex).claer();

  • Problem with access specifier and static???

    I've a question. I saw a code written for Sun's Java Tutorial. The program had three class methods and all of them start like this:
    static public void methodName1{
    static public void methodName2{
    and
    static public void main(String[] args){
    My question is why the keyword static was used first? Why not access specifier? I mean what's the reason behind it? Is there any difference between them?
    Thanks in advance.
    --DM

    The order doesn't matter. The programmer thought it was a good idea for some reason. I might be tempted to do it if I had static and instance methods with the same name or something like that.
    public static void myMethod() {
    public void myMethod() {
    or
    static public void myMethod() {
    public void myMethod() {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Query regarding database access segregation using os authentication in windows environment

    Hi ,
    I have a query regarding database access segragation using os authentication (like sqlplus "/ as sysdba") in windows environment.Let me briefly explain my requirement:-
    Suppose you have two DBA`s viz DBA1 and DBA2 and 4 databases resideds in a windows server say A,B,C & D.Now I want to set up such a way if DBA1 logs into the server then he can login to database A and B only using OS authentication and DBA2 can login to database C and D only using OS authentication.
    Please let me know how to do setup for this requirement.
    Database version is 11.2.0.3

    1494629, I am not a Windows person but if there is any way to do this I suspect some additional information is necessary:
    Are the DBA users members of the Administrators Group ?
    Do all 4 database share the same $ORACLE_HOME ?
    I suspect if either answer above is yes then this is not possible, but like I said I am not a Windows person.  I would just ask for two servers and the associated licensing to be acquired.  The requirement to spend money to do something management wants usually elimanates the request in my world.
    HTH -- Mark D Powell --

  • Java inner class access specifiers

    public class MyClass1 {
    public static void main(String argv[]){ }
    /*Modifier at XX */ class MyInner {}
    What modifiers would be legal at XX in the above code?
    1) public
    2) private
    3) static
    4) friend

    Iam a newbie to javaI don't care. I still assume you have a brain and expect you to use it.
    and iam struck with this
    question, iam getting a compile time error for any
    access specifiers mentioned as options, but the
    answers given by my superior are 1,2,3, are
    correct..Then you made a typo or whatever. Make sure you eliminate the problems that are not "illegal access modifier" errors.
    What good is knowing the reply to this if you can't even write an example?

  • Can I password protect access to Time Machine??

    Hey guys ..
    Ive just switched over from PC to mac. So far Im loving it and doubt Ill ever use a PC again.
    I do have a question about Time Machine though. Is there a way to password protect access to the Time Machine interface ?
    Cheers
    Darren

    Can't help with the TM stuff, since I don't use it, and will leave that discussion to macwiz1220; however, since you're new to Macs, once you sort out your issue, see these:
    Switching from Windows to Mac OS X,
    Basic Tutorials on using a Mac,
    Mac 101: Mac Essentials,
    Anatomy of a Mac,
    MacFixIt Tutorials,
    MacTips, and
    Switching to the Mac: The Missing Manual, Leopard Edition.
    Additionally, *Texas Mac Man* recommends:
    Quick Assist.
    Welcome to the Switch To A Mac Guides,
    Take Control E-books, and
    A guide for switching to a Mac.

Maybe you are looking for

  • How to delete images from folder which are not in the database

    I am created windows form i wont to delete images from the folder where i have stored images but i only want to delete those images which are not in the data base. i don't know how it is possible . i have written some code private void button1_Click(

  • Prompt Labels missing on the dashboard after upgrade to 11.1.1.6.9

    We upgraded to 11.1.1.6.9 and all the dashboard prompt labels where the labels are not customized are missing. Has anyone else encountered this issue? Thanks Edited by: 947403 on Mar 20, 2013 9:06 AM

  • How can I print commentaries made to a pdf-document with Adobe reader ?

    My message and question is contained in the header of this message. I am receiving occasionally  PDF- documents as an attachement  to an email for examination. I can attach comments to special parts of the document, which are indicated by tags in the

  • CFPOP and digital signatures

    Emails - Exchange 2003 mail server - that use "Digital signatures" do not show any Body text. Either in the "BODY" or in the "TEXTBODY" fields. Are there any work arounds or fixes for this? Thanks,

  • Single monitor goes black, 2 monitors work fine

    I was using a friend's old PPC G5, and the Dell flat screen he has went black. Couldn't get it to stay on.  So I hooked up another monitor in the 2nd monitor socket, and the 1st monitor unexpectedly came on. Both displays worked fine. But if I discon