原代码及运行结果如下
ParentClass:
package com.design;
class ParentClass {
public static String staticField = "父类静态变量";
public final String finalField = "父类常量";
public static final String staticFinalField = "父类静态常量";
public static void getStr(){
System.out.println("child output");
}
}
SubClass:
package com.design;
public class SubClass extends ParentClass {
public static String staticField = "子类静态变量";
public final String finalField = "子类常量";
public static final String staticFinalField = "子类静态常量";
public static void getStr(){
System.out.println("child output");
}
public static void main(String[] args) {
[b]//这里到底发生了什么? [/b]
ParentClass subClass = new SubClass(); //(1)
System.out.println(subClass.staticField);
System.out.println(subClass.finalField);
System.out.println(subClass.staticFinalField);
subClass.getStr();
[b]//为什么与(1)不同呢 [/b]SubClass subClass2 = new SubClass();
System.out.println(subClass2.staticField);
System.out.println(subClass2.finalField);
System.out.println(subClass2.staticFinalField);
subClass2.getStr();
}
}
运行结果:
父类静态变量
父类常量
父类静态常量
child output
子类静态变量
子类常量
子类静态常量
child output
ParentClass:
package com.design;
class ParentClass {
public static String staticField = "父类静态变量";
public final String finalField = "父类常量";
public static final String staticFinalField = "父类静态常量";
public static void getStr(){
System.out.println("child output");
}
}
SubClass:
package com.design;
public class SubClass extends ParentClass {
public static String staticField = "子类静态变量";
public final String finalField = "子类常量";
public static final String staticFinalField = "子类静态常量";
public static void getStr(){
System.out.println("child output");
}
public static void main(String[] args) {
[b]//这里到底发生了什么? [/b]
ParentClass subClass = new SubClass(); //(1)
System.out.println(subClass.staticField);
System.out.println(subClass.finalField);
System.out.println(subClass.staticFinalField);
subClass.getStr();
[b]//为什么与(1)不同呢 [/b]SubClass subClass2 = new SubClass();
System.out.println(subClass2.staticField);
System.out.println(subClass2.finalField);
System.out.println(subClass2.staticFinalField);
subClass2.getStr();
}
}
运行结果:
父类静态变量
父类常量
父类静态常量
child output
子类静态变量
子类常量
子类静态常量
child output