Java private, protected, public and default

You are a Java programmer, so you know what I am talking about. public modifiers make a method or field accessible from anywhere in the application. That is the simple part. But can you tell me the difference between protected and package private? (Hint: package private is the protection of a method or a field when you do not write any access modifier in front of it. Be aware! I lie!) My interview experience is that many do not know. Do I consider that as a no go for a Java developer? Not really. You may still be a good Java developer even if you do not know that. Perhaps now you will look it up somewhere. Perhaps the Java spec is a good document to start.

I’ll tell you something more interesting.

 

Literally, none of the candidates know what private is. And you, reading this article, also do not know.

Ok, this is very provocative. You may be one of the few who happen to fill his brain with such a useless information and you may even have read the Java specification.

Most Java programmers think that private methods and fields are accessible only from within the class. Some even think that only from within the object instance. They believe that:

public class PrivateAccessOtherObject {
    public PrivateAccessOtherObject(int i) {
        this.i = i;
    }
    private int i;
    void copyiTo(PrivateAccessOtherObject other){
        other.i = i;
    }
}

is not possible. (It is.)

So what is private?

The recent JLS says that A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

The example in the Java specification is not the best describing the rule. Perhaps that is just a simple example. Something like this may be better explaining the concept:

public class PrivateFieldsContainingClass {
    private static class NestedClass {
        private int i;
    }
    private NestedClass nestedClassInstance = new NestedClass();
    void set(int i) {
        nestedClassInstance.i = i;
    }
    int get() {
        return nestedClassInstance.i;
    }
}

The field i is accessible from the enclosing class as well as from inside the NestedClass. This example is also simple but more to the point that the specification example misses. Is there any real use of this possibility? Not really.

Bonus question: why did I say I was lying?

Reference: Java private, protected, public and default from our JCG partner Peter Verhas at the Java Deep blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

4 Responses to "Java private, protected, public and default"

  1. I think you the stuff you lie is about default access.
    So in the case of no modifier (default), whether the subclass can see it’s superclass’s methods/fields depends on the location of the subclass . If the subclass is in another package, then the answer is it can’t. If the subclass is in the same package then it CAN access the superclass methods/fields.
    One example:

    package myarea;

    public class MyHome{
    private int frontDoorLock;
    public int myAddress;
    int defaultWifiPaswd;
    }

    package myarea;

    public class MyBedroom{
    public static void main(String[] args) {
    MyHome a = new MyHome();
    int v1 = a.myAddress; // works
    int v2 = a.defaultWifiPaswd; // works
    int v3 = a.frontDoorLock; // doesn’t work

    }
    }

    package neighbourArea;

    import myarea.MyHome;

    public class NeighbourHome{
    public static void main(String[] args) {
    MyHome a = new MyHome();
    int v1 = a.myAddress; // works
    int v2 = a.defaultWifiPwd; // doesn’t work
    int v3 = a.privateVar; // doesn’t work
    }

    Thanks
    Sankalp

  2. Peter Verhas says:

    Dear Sankalp,

    your example is a very good example how package private fields and methods work, where they are accessible from and where and when are they unreachable. The actual lie is somewhere else. If you consider the statement:

    The statement

    “package private is the protection of a method or a field when you do not write any access modifier in front of it”

    is a bit vague. Not precise. Think of interfaces!

  3. Sankalp Suryawanshi says:

    Exactly Peter!

    Actually Interface’s thought came to my mind, because all fields defined in interface are always public (and even static +final). Am I missing some more you hinted ? :)

    Thanks
    Sankalp

Leave a Reply


five × 4 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close