• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overriding default methods  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have just got a practice exam question wrong and I can't see why. The question was similar to this:

From what I understand when you override you can only use the same or less restrictive access modifiers for the method, so I said that the above code would not compile. However when running the code it does compile! How is a protected access modifier less restrictive than a default modifier?

I would have thought that a method that can be accessed by all classes in the same package is less restrictive than a method that can only be accessed though inheritance.
 
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This page probably makes it clear. (protected allows package access too, plus subclass access)
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David Kay wrote:I have just got a practice exam question wrong and I can't see why. The question was similar to this:

From what I understand when you override you can only use the same or less restrictive access modifiers for the method, so I said that the above code would not compile. However when running the code it does compile! How is a protected access modifier less restrictive than a default modifier?

I would have thought that a method that can be accessed by all classes in the same package is less restrictive than a method that can only be accessed though inheritance.


well, the method Base.doSomething() can't be accessed from a subclass of Top, but a subclass of Top can acess the method Top.doSomething(), for Java they are two different methods. At final the method Top.doSomething() keep acting like a gateway to the method Base.doSomething.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some people get confused because protected access is different in C++ from Java™. In C++ it is subclasses only.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!