class Base {
String var = "Base's var";
static String staticVar = "Base's static var";
void method() {
System.out.println("call Base's method");
}
static void staticMethod() {
System.out.println("call Base's static method");
}
}
String var = "Base's var";
static String staticVar = "Base's static var";
void method() {
System.out.println("call Base's method");
}
static void staticMethod() {
System.out.println("call Base's static method");
}
}
public class Sub extends Base {
String var = "Sub's var";
static String staticVar = "Sub's static var";
void method() {
System.out.println("call Sub's method");
}
static String staticVar = "Sub's static var";
void method() {
System.out.println("call Sub's method");
}
static void staticMethod() {
System.out.println("call Sub's static method");
}
String subVar = "Var only belonging to Sub";
void subMethod(){
System.out.println("Call Method only beloging to Sub");
}
System.out.println("call Sub's static method");
}
String subVar = "Var only belonging to Sub";
void subMethod(){
System.out.println("Call Method only beloging to Sub");
}
public static void main(String[] args) {
Base who = new Sub();
System.out.println("who.var="+who.var);//Base's var
System.out.println("who.staticVar="+who.staticVar);//Base's static var
who.method();//call sub's method
who.staticMethod();//call Base's static method
}
}
Base who = new Sub();
System.out.println("who.var="+who.var);//Base's var
System.out.println("who.staticVar="+who.staticVar);//Base's static var
who.method();//call sub's method
who.staticMethod();//call Base's static method
}
}
(
1
)对于一个引用类型的变量,
Java
编译器按照它声明的类型来处理。
Base who = new Sub();
who.subVar = "123"; // 编译出错, Base 中没有 subVar
who.subMethod(); // 编译出错, Base 中没有 subMethod() 方法
如果要访问 Sub 类中成员,必须通过强制类型的转换。
Base who = new Sub();
((Sub)who).subVar = "123";
((Sub)who).subMethod();
Base who = new Sub();
who.subVar = "123"; // 编译出错, Base 中没有 subVar
who.subMethod(); // 编译出错, Base 中没有 subMethod() 方法
如果要访问 Sub 类中成员,必须通过强制类型的转换。
Base who = new Sub();
((Sub)who).subVar = "123";
((Sub)who).subMethod();
(
2
)对于一个引用类型的变量,运行时
Java
虚拟机按照它实际引用的对象来处理。例如以下代码虽然编译通过,但运行时抛出
ClassCastException
运行时异常。
Base who = new Base();
Sub s = (Sub)who; // 运行时抛出 ClassCastException
在运行时,子类的对象可以转换为父类类型,而父类的对象实际上无法转换为子类类型。
Base who = new Base();
Sub s = (Sub)who; // 运行时抛出 ClassCastException
在运行时,子类的对象可以转换为父类类型,而父类的对象实际上无法转换为子类类型。
(
3
)在运行时环境中,通过引用类型变量来访问所应用对象的方法和属性时,
Java
虚拟机采用以下绑定规则。
3.1 实例方法与引用变量实际引用的对象的方法绑定,这种绑定属于动态绑定,因为是在运行时由 JAVA 虚拟机动态决定的。
3.2 静态方法与引用变量所声明的类型的方法绑定,这种绑定属于静态绑定,因为实际上是在编译阶段就已经做了绑定。
3.3 成员变量(包括实例变量和静态变量)与引用变量所声明的类型的成员变量绑定,这种绑定属于静态绑定,因为实际是在编译阶段就已经做了绑定。
3.1 实例方法与引用变量实际引用的对象的方法绑定,这种绑定属于动态绑定,因为是在运行时由 JAVA 虚拟机动态决定的。
3.2 静态方法与引用变量所声明的类型的方法绑定,这种绑定属于静态绑定,因为实际上是在编译阶段就已经做了绑定。
3.3 成员变量(包括实例变量和静态变量)与引用变量所声明的类型的成员变量绑定,这种绑定属于静态绑定,因为实际是在编译阶段就已经做了绑定。
可以采取两种措施来禁止继承:
1 把类声明为 final 类型。
2 把这个类的构造方法声明为 private 类型,然后通过一些静态方法来负责自身的构造。
1 把类声明为 final 类型。
2 把这个类的构造方法声明为 private 类型,然后通过一些静态方法来负责自身的构造。