Reputation: 73
I'm new to the syntax of Java and was looking at a question in regards to the protected access modifier. Titled "Protected member access from different packages in java - a curiosity".
Protected member access from different packages in java - a curiosity
In that question the following code was referred to:
package packageOne;
public class Base{
protected void display(){
system.out.println("in Base");
}
}
package packageTwo;
public class Derived extends packageOne.Base{
public void show(){
new Base().display();//this is not working throws compilation error that
//display() from the type Base is not visible
new Derived().display();//is working
display();//is working
}
}
My question is in regard to the last line of code.
display(); //is working
For me, this line does not compile and that makes sense, because the method is refereed to from a static context.
I comprehend the rules around using protected members and reference variables types, but using a non static protected member without a reference variable seems to confuse me.
Reading the answers, I do not see anyone else having a problem with this, except for the last answer. But that answer does't seem to relate to the question asked.
Sorry this question might seem pedantic or primitive, but it is bugging me as this breaks OO programming.
Am I missing something here? please advice,
Thanks
Upvotes: 1
Views: 78
Reputation: 95
The method is not referred to from a static content.
show()
is an instance method.
Are you trying the same code, but within a main() ?
Upvotes: 0
Reputation: 1074545
For me, this line does not compile and that makes sense, because the method is refereed to from a static context.
No, it isn't. It's inside an instance method (show
). In Java, within instance methods, the this.
is optional when referring to other instance methods and fields. E.g., if the call to display
is in an instance method (and it is in that code), display();
and this.display();
are exactly the same thing.
Upvotes: 6