2015-09-07 11:44:36 -06:00
|
|
|
// reuse/FinalOverridingIllusion.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// It only looks like you can override
|
2016-01-25 18:05:55 -08:00
|
|
|
// a private or private final method
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
class WithFinals {
|
|
|
|
// Identical to "private" alone:
|
2015-12-02 09:20:27 -08:00
|
|
|
private final void f() {
|
|
|
|
System.out.println("WithFinals.f()");
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
// Also automatically "final":
|
2015-12-02 09:20:27 -08:00
|
|
|
private void g() {
|
|
|
|
System.out.println("WithFinals.g()");
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
class OverridingPrivate extends WithFinals {
|
|
|
|
private final void f() {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("OverridingPrivate.f()");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
private void g() {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("OverridingPrivate.g()");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class OverridingPrivate2 extends OverridingPrivate {
|
|
|
|
public final void f() {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("OverridingPrivate2.f()");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
public void g() {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("OverridingPrivate2.g()");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class FinalOverridingIllusion {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
OverridingPrivate2 op2 = new OverridingPrivate2();
|
|
|
|
op2.f();
|
|
|
|
op2.g();
|
|
|
|
// You can upcast:
|
|
|
|
OverridingPrivate op = op2;
|
|
|
|
// But you can't call the methods:
|
2015-12-18 11:28:19 -08:00
|
|
|
//- op.f();
|
|
|
|
//- op.g();
|
2015-06-15 17:47:35 -07:00
|
|
|
// Same here:
|
|
|
|
WithFinals wf = op2;
|
2015-12-18 11:28:19 -08:00
|
|
|
//- wf.f();
|
|
|
|
//- wf.g();
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
OverridingPrivate2.f()
|
|
|
|
OverridingPrivate2.g()
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|