Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Diff. Bet. "protected" and "default" access specifiers

gnv_ravindragnv_ravindra Member Posts: 46
Friend,
I just started learning java n want to know the clear difference between "protected" and "default" access specifiers. Please give me the difference in detail and if possible with clear example.
Thank You.
ravi.

Comments

  • aveachaveach Member Posts: 5
    : Friend,
    : I just started learning java n want to know the clear difference between "protected" and "default" access specifiers. Please give me the difference in detail and if possible with clear example.
    : Thank You.
    : ravi.
    :

    Ok this is how i understand it,
    "default" access is what is known as the package access. If you do not declare a field or method as 1)public 2)protected or 3)private java automatically assigns it as package or "default". This means that the field or method is only accessible by other classes inside the same package. You might have seen some code examples that contain the code "package ......" that occurs somewhere near the beginning of the code. This is declaring what package the class is a prt of. And only other classes that are also a part of this package can access fields/methods that have default/package access.

    protected access is the same as default except it also makes the methods/fields available to any class which "extends" that class.
    For instance if you look at the Java API http://java.sun.com/j2se/1.4.2/docs/api/
    you may notice some classes such as String that say ".... extends Object" This means a String IS A Object and therefor any methods/fields that are protected in the Object class are now made available to the String class since String extends Object.
    default=accessible by anyone in the package
    protected=accessible by package and any subclasses(anyone who extends that class)
    Hope this helps a little.
Sign In or Register to comment.