Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in Java
Prev Contents / Index Next

Name hiding

If a Java base class has a method name that’s overloaded several times, redefining that method name in the derived class will not hide any of the base-class versions (unlike C++). Thus overloading works regardless of whether the method was defined at this level or in a base class:

// Overloading a base-class method name in a derived class
// does not hide the base-class versions.
import com.bruceeckel.simpletest.*;

class Homer {
  char doh(char c) {
    return 'd';
  float doh(float f) {
    return 1.0f;

class Milhouse {}

class Bart extends Homer {
  void doh(Milhouse m) {

public class Hide {
  private static Test monitor = new Test();
  public static void main(String[] args) {
    Bart b = new Bart();
    b.doh(new Milhouse());
    monitor.expect(new String[] {
} ///:~

You can see that all the overloaded methods of Homer are available in Bart, even though Bart introduces a new overloaded method (in C++ doing this would hide the base-class methods). As you’ll see in the next chapter, it’s far more common to override methods of the same name, using exactly the same signature and return type as in the base class. It can be confusing otherwise (which is why C++ disallows it—to prevent you from making what is probably a mistake).
Thinking in Java
Prev Contents / Index Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire