|
TestOverrideOverload.java
|
import java.io.*;
public class TestOverrideOverload {
public static void main (String[] args) throws IOException {
SubBase sub = new SubBase(1);
Base base = sub;
// Java compiler computes access to member variables
// at compile time
System.out.println(base.x); //9
System.out.println(sub .x); //0
// Java dynamically binds methods at runtime
System.out.println(base.doSomething(3.0, 5)); //8
System.out.println(sub .doSomething(3.0, 5)); //8
System.out.println(sub .doSuperSomething(3.0, 5)); //17
// Method doSuperSomething(double, int) not found
// in class Base
//System.out.println(base.doSuperSomething(3.0, 5));
// be very careful to see the result and think why?
// Change f() to public in Base and SubBase, then run it again
// notice the difference in output
SubSubBase c = new SubSubBase(1);
System.out.println(c.g());
System.in.read();
}
}
class Base {
int cnt;
int x = 9;
Base(int n) {
cnt = n;
}
private int f() { return 0;}
void doSomething(int n) {
}
// different signature is oK
int doSomething(double d) {
return (int)d;
}
// Methods can't be redefined with a different return type
//int doSomething(int n) {
// return n;
//}
int doSomething(double d, int a) {
return (int)d + a + x;
}
public void m() {
}
}
class SubBase extends Base{
int x;
SubBase(int n){
// this must be explicitly called
super(n);
}
private int f() { return 1;}
public int g() { return f();}
// Methods can't be redefined with a different return type
//int doSomething(int n) {
// return n;
//}
int doSomething(double d, int a) {
return (int)d + a + x;
}
int doSuperSomething(double d, int a) {
return super.doSomething(d, a);
}
// method can't be overriden to be more private
//protected void m() {
//}
}
class SubSubBase extends SubBase{
SubSubBase(int n){
// this must be explicitly called
super(n);
}
public int f() { return 2;}
}
Last updated: 12-10-2002
Copyright © 1999 - 2003 Roseanne Zhang, All Rights Reserved