先看下代码:
- 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) {
- //这里到底发生了什么?
- ParentClass subClass = new SubClass(); //(1)
- System.out.println(subClass.staticField);
- System.out.println(subClass.finalField);
- System.out.println(subClass.staticFinalField);
- subClass.getStr();
- //为什么与(1)不同呢 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
我想问的是父类子类有相同的变量声明,为什么变量取决于引用而不是实际的对象? |