-1

I have generic class with some fields with "protected" scope. Is it possible to override or something this scope in an inherited class? Here's example of my generic (extended) class:

public abstract class BaseDAO<T extends Entity> {

protected MongoClient client;
protected MongoCursor<Document> cursor; }

So, how, if be the most specific, to change "protected" to "private" in my inheriting classes?

Google doesn't understand my requests and offers the most basic tutorials about inheritance, which don't give answer for my question. Tried to search here too by some tags a la "java scope override" and something. Didn't work.

Thanks for feedback!

nyarian
  • 4,085
  • 1
  • 19
  • 51
  • 1
    you can't .... it is as simple as that. – Stultuske May 29 '17 at 20:56
  • 1
    If you re-declare fields in a subclass you will hide rather than override (see: https://stackoverflow.com/questions/9414990/if-you-overwrite-a-field-in-a-subclass-of-a-class-the-subclass-has-two-fields-w). In terms of methods, you can only increase the visibility (e.g. protected to public) and not decrease (protected to private). – d.j.brown May 29 '17 at 21:22
  • yes, i know that super.fieldName and just fieldName are differend variables. but you answered my question anyway, thanks! – nyarian May 30 '17 at 07:00

2 Answers2

-1

This is not possible, and would not respect the Liskov substitution principle, since your inherited class would "hide" the field (i.e. your inherited class could not be seamlessly swapped with BaseDAO).

Sir4ur0n
  • 1,753
  • 1
  • 13
  • 24
  • So, the only way to create private fields in inheritors is not to inheritate this fields, am i right? – nyarian May 30 '17 at 06:59
  • Not sure what you mean here. Your subclass will always inherit the parent fields, there's nothing you can do about it. But you can definitely add private fields in your subclass. – Sir4ur0n May 31 '17 at 07:29
-1

you already received correct answers. You can't decrease visibility only increase it. (as @d.j.brown said)

So you can override parent methods and increase visibility to public but you can't decrease it to private.

Andriy Rymar
  • 313
  • 3
  • 8