-3

EDIT: sorry for the inconvenience, it was lack of understanding of the concept. u can simply ignore this question.

i am pretty sure that we can't inherit neither final nor private variables. but, why should we declare variables as final when declaring them as private can stop them from inheriting.

i even know that the value of final variables can not be changed neither by a base class or derived class. what i want to infer is whether declaring a variable as private or final really show any difference while inheriting.

PS: I could not get clarification anywhere from the internet. each source explaining them separately even though both of them show almost same behaviour while inheriting them.

  • 2
    You don't need "the internet" to give you an answer: declare a class with a private field and a final field; then declare a subclass, and look at which of the two fields are inherited. – Andy Turner Jul 21 '18 at 18:28
  • 1
    `private` and `final` are 2 completly different things, accessabilty and writeability. So making a variable private indicates it is only used in that exact class. Whereas making it final just sets it to readonly. TBH I don't understand your question – Lino Jul 21 '18 at 18:30

1 Answers1

3

i am pretty sure that we can't inherit neither final nor private variables

This is true for private fields, not for final fields. Final fields are inherited (non-private ones, that is). Whether they can be modified or not has nothing to do with inheritance.

With regards to inheritance, final has significance when it comes to inherited methods (a final method cannot be overridden) and classes' ability to be inherited (a final class cannot be extended).

why should we declare variables as final when declaring them as private can stop them from inheriting.

You declare a variable as final for a different reason. private encapsulates the field, whereas final makes it impossible to reassign.

ernest_k
  • 44,416
  • 5
  • 53
  • 99