Re: Private methods can't be overridden?
 
Johannes Schaub (litb) wrote:
I heard today that in Java you cannot override private methods. I'm 
wondering about this snippet:
class Printer {
  public void print() {
    preparePrint();
    doPrint();
    finalizePrint();
  }
  private abstract void doPrint();
This is an illegal statement.  Did you try to compile it?
Since a 'private' member cannot be inherited, and an 'abstract' method by 
definition must be inherited, the combination 'private abstract' is illegal.
You should read the Java tutorial on java.sun.com and other introductory texts.
<http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html>
<http://java.sun.com/docs/books/tutorial/java/IandI/subclasses.html>
<http://java.sun.com/docs/books/tutorial/java/IandI/abstract.html>
Google for more.
};
class LaserPrinter extends Printer {
  private void doPrint() {
Since 'private' methods are not inherited, this is a completely separate 
method from the superclass's (illegal as written) 'private' method of the same 
signature.
Because 'private' methods are not inherited, the superclass 'print()' method 
will call only the superclass 'doPrint()' and will not polymorphically invoke 
that of the subclass.
    // print stuff
  }
};
I wonder why i [sic] can't write it like this. 
Because the purpose of 'private' is to prevent just that.
Users of "Printer" and derived classes of Printer are 
not supposed to call "doPrint" directly, so i [sic] would 
like to make it private. 
You cannot make it 'private' and also have it inherit.  You can make 
'doPrint()' either 'protected' (making it visible to all subclass 
implementations whether or not in the same package) or package-private 
(default) visibility, making it visible to all implementations in the same 
package.
I heard from people that do C++ that it is a good idea to make virtual 
methods private and public functions non-virtual (non-virtual-interface).
Java is not C++.
What is the reason Java doesn't follow this path? 
Because Java is its own language with its own rules.  It isn't C++, it isn't 
BASIC, and it isn't FORTRAN.
-- 
Lew