siva chaitanya wrote: but why cant we create an object of super class and access the protected variable in subclass which is in different package
And you're again asking the same question..
Look, there are three cases: -
1). Public members -> Accessible globally through the instance of the corresponding class
2). Private members -> Accessible nowhere else except in the same class
3). Protected Members -> This is a special case. Accessible in the same class or subclass (even in different package)
Now, when it says, accessible in subclass in different package, it means through inheritance.. (And now, you will ask what does this mean ??)
Suppose class A has a protected member protVar. And, we have a subclass B of A.
Now the
protVar of class A will be accessible in class A (of course) and in class B (only through the instance class B, but not directly through class A instance)..
So, you can access it in either of the following two ways: -
B obj = new B()
obj.protVar; or
protVar; (notice implicit 'this' keyword)
You can not just access it through the instance of class A, if you are outside class A (no matter where you are)