FAQ

Java

JSP

Servlet


Advertisement



Can private method be overridden?

The private methods are not inherited by subclasses and you cannot be overridden by subclasses. According to Java Language Specification (8.4.8.3 Requirements in Overriding and Hiding), "Note that a private method cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass."

What does it mean? It means you can have a private method has the exact same name and signature as a private method in the superclass, but you are not overriding the private method in superclass and you are just declaring a new private method in the subclass. The new defined method in the subclass is completely unrelated to the superclass method. A private method of a class can be only accessed by the implementation in its class. A subclass cannot call a private method in its superclasses.

For example,

class Super {
private int x;
public double y;
public Super() {
System.out.println("-- Super --");
print1();
print2();
print3();
print4();
}
private void print1() { System.out.println("Super::print1()" + (x + 1)); }
private void print2() { System.out.println("Super::print2()" + (x + 2)); }
public void print3() { System.out.println("Super::print3()" + (x + 3)); }
private void print4() { System.out.println("Super::print4()" + (x + 4)); }
}

class Sub extends Super {
public Sub() {
System.out.println("-- Sub --");
/* print1(); */ //compile-time error
print2();
print3();
print4();
}
public static void main(String[] args) {
new Sub();
}

public void print2() { System.out.println("Sub::print2()"+(y+2)); }
// private void print3() { System.out.println("Sub::print3()"+(y+3));}
//Error
private void print4() { System.out.println("Sub::print4()"+(y+4)); }
}

The output is

-- Super --
Super::print1()1
Super::print2()2
//If you can override private method, it should print out "Sub::print2()2.0"
Super::print3()3
Super::print4()4
//If you can override private method, it should print out "Sub::print4()4.0"
-- Sub --
Sub::print2()2.0
Super::print3()3
Sub::print4()4.0


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |