views:

1253

answers:

5

In java, there's three levels of access:

  • Public - Open to the world
  • Private - Open only to the class
  • Protected - Open only to the class and its subclasses (inheritance).

So why does the java compiler allow this to happen?

TestBlah.java:

public class TestBlah {

    public static void main(String[] args) {
        Blah a = new Blah("Blah");
        Bloo b = new Bloo("Bloo");
        System.out.println(a.getMessage());
        System.out.println(b.getMessage()); //Works
        System.out.println(a.testing);
        System.out.println(b.testing); //Works
    }
}

Blah.java:

public class Blah {
    protected String message;

    public Blah(String msg) {
        this.message = msg;
    }

    protected String getMessage(){
        return(this.message);
    }   
}

Bloo.java:

public class Bloo extends Blah {
    public Bloo(String testing) {
        super(testing);
    }
}
+9  A: 

Because protected means subclass or other classes in the same package.

Software Monkey
+7  A: 

Actually it should be:

Open only to the classes on the same package the class and its subclasses (inheritance)

That's why

OscarRyz
+3  A: 

You're able to call b.getMessage() because b is of type Bloo, which extends Blah, and getMessage() is protected. Protected, as you mentioned, allows subclasses to access the method.

You've got the following errors, though:

  • Calling super() with no arguments in the Bloo constructor is an error. The compiler can't find the no-parameter Blah constructor because you defined one with a String parameter.
  • Calling new Blah() in TestBlah main method is an error for the same reason as above.
  • Referring to a.testing and b.testing is an error because you didn't define the variable testing for any class.
Bill the Lizard
He heh I gues I'll never know if he did that on purpose. Hey that's funny the lizard answering to the dragon. :)
OscarRyz
+4  A: 

To be more specific, you're expecting protected to work as it does in C++.

However, in Java, it has a different meaning. In Java, a protected method is available to the class (obviously), all the other classes in the same package and any subclasses of this class. Classes in other packages will not have access unless they subclass this original class.

See this similar question for more specific information on inheritance markers.

Personally, I almost never use protected. I develop applications rather than frameworks so I'm much more likely to define public methods, private data and, quite often, mark my whole class as final.

Bob Cross
+4  A: 

There are actually four levels of access: "public", "protected", "private" & default also known as package private or package protected. Default limits accessibility to the package. Default is quite useful and I use it frequently.

Julien Chastang