OnJava8-Examples/reuse/FinalOverridingIllusion.java

57 lines
1.3 KiB
Java
Raw Normal View History

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.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// It only looks like you can override
// a private or private final method.
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:
//! op.f();
//! op.g();
// Same here:
WithFinals wf = op2;
//! wf.f();
//! wf.g();
}
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
*/