lsrinu said:
Suppose I dont want to inherit my super class methods in the sub class,
here I can write all my methods with final, instead of this if I can
declare all the methods are private in this case also these are not
inherited, what is the basic difference between these two, where we use
private, where we use final
The final modifier prevents someone from overriding a method. It does
NOT prevent the method from being inherited; merely from being
overridden.
The private modifier does this, and more. Specifically, private
prevents the method from called OR overridden by any code except the
immediate implementation of that class. Because the private method is
not visible outside the class, the subclass can declare a new method
with that same signature, but it will NOT override the private method
from the superclass. (It's worth noting that Java borrows many concepts
from C++, but this is not one of them; it's a notable difference from
C++'s access specifiers.)
As a side note: whether the private modifier prevents the private method
from being "inherited" is a question of terminology; in the terminology
used by the Java Language Specification, private methods are not
inherited... but don't let that confuse you into thinking that they
can't execute on instances of a subclass. You would just need an
accessible path to get there. For example, a public method in the
superclass may still call the private method, and if it is not
overridden or if it's called via the 'super' keyword from somewhere in
the subclass implementation, then you have the path you need to execute
the private method. You should probably not assume that others are
thinking of the same precise definition of "inherited" if you are
communicating with other people about Java.
Hope that helps,