Neil Walker
Neil Walker

Reputation: 6868

java protected why is this working through non-inheritance?

I'm obviously missing the obvious in this but given:

package a;
public class Class1 {
    protected int a=1;
}

package b;
import a.*;

public class Class2 extends Class1 {
    Class2() {
        Class1 c1=new Class1();
        Class2 c2=new Class2();
        System.out.println(a);     //1
        System.out.println(c1.a);  //2
        System.out.println(c2.a);  //3
    }
}

I know //1 is fine due to being used through inheritance and //2 fails because it's not being access through inheritance, but why is //3 ok too? I thought variable a was being accessed through a new object and a resides in Class1?

Thanks.

Upvotes: 1

Views: 109

Answers (4)

Tobb
Tobb

Reputation: 12225

Since any object of Class2 is-a Class1, it can access all of Class 1's member variables with scopes default, protected and public.

Besides, trying to understand scope and inheritance rules through working with objects that are of the class you are using to play with scopes/inhertiance is not a good idea, since it works in a different way than through a third-party (which is the most common use.)

For instance, this is allowed:

public class Something {
   private int something;

   public int stealSomething(final Something otherthing) {
       return otherthing.something;
   }
} 

Try making a third class, that is not in the hierarchy of the classes you are using to test.

Upvotes: 4

Rohit Jain
Rohit Jain

Reputation: 213401

why is //3 ok too?

And why shouldn't it be ok? Given that Class2 is the subclass of Class1, so a protected fields of Class1 are accessible through the instance of Class2. And that is what you are doing here. c2 is an instance of Class2, and a field is visible for it.

NOTE: A protected member is accessible to any direct subclass, whether in same package or in different package.

I thought variable a was being accessed through a new object

Yeah, that's true.

and a resides in Class1?

That really doesn't matter here. As far as a is accessible to Class2 instance, it is valid.

And just FYI, your code will die of StackOverflowError. You need to take care of it.

Upvotes: 3

Daniel Pereira
Daniel Pereira

Reputation: 2785

When you are manipulating an object inside its class, you have full access to all his attributes, including the private ones. As c2 is a instance of Class2 and you are manipulating it inside the Class2 code, you can see the protected attribute.

Upvotes: 4

arcy
arcy

Reputation: 13153

I don't understand the problem.

Class1 has a variable named 'a'. Since it is 'protected', that variable is visible within any object of Class1 and any object of a class extending Class1.

If 'a' were private, then it would not be visible this way in objects of classes extending Class1.

Upvotes: 1

Related Questions