Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Can private method be overridden?

  xyzws.com        2011-10-06 03:57:14       3,445        0    

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

Source : http://www.xyzws.com/Javafaq/can-private-method-be-overridden/28

JAVA  PRIVATE METHOD  OVERRIDDING  IMPOSSIB 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.