java继承类相互引用加上静态属性的困扰

本文通过一个具体的Java代码示例,详细解析了Java中父类与子类的继承关系,包括实例变量、静态变量以及方法覆盖等核心概念。通过调试过程揭示了对象创建时属性赋值的顺序,并展示了不同情况下方法调用的行为。
在网上看到这样一段代码
class father
{
    
public String var="father";
    
public static String staticvar="staticfather";
    
void method()
    
{
        System.out.println(
"father method");
    }

    
static void staticmethod()
    
{
        System.out.println(
"father staticmethod");
    }

}

class son extends father
{
    
public String var="son";
    
public static String staticvar="staticson";
    
void method()
    
{
        System.out.println(
"son method");
    }

    
static void staticmethod()
    
{
        System.out.println(
"son staticmethod");
    }

}

class goodClass
{
    
public static void test()
    
{
        father f
=new son();
        System.out.println(
"f.var="+f.var);
        System.out.println(
"f.staticvar="+f.staticvar);
        f.method();
        f.staticmethod();
    }


}

public class Inherit {

    
/**
     * 
@param args
     
*/

    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
        goodClass.test();
    }


}

结果是:
f.var=father
f.staticvar
=staticfather
son method
father staticmethod

如果去掉属性的static, 结果是不变的

如果给method加上static属性,结果如下
f.var=father
f.staticvar
=staticfather
father method  ;;已经改变
father staticmethod

如果测试时用
son f = (son)new father();
编译没问题,但执行时会报cast exception

单步测试结果, 在
father f=new son();
下断点

启动eclipse debug模式, 注意按F5, 即step into
看看整个流程

执行如下:
father : public static String staticvar="staticfather";
   son:      public static String staticvar="staticson";
   son:      构造函数    //这里没有
   father:  构造函数
   构建this指针: 此时debug 的 variables窗口 this下两个var, 此时为null
   father:   public String var="father";  // 赋值给this第一个var
   son :      public String var="son";    // 复制给this第二个var
   this 指针 赋给 f
  
   完成此句

两个var, 调用f.var的时候取得是第一个, "father"
static属性是全局的,这个不受 f 控制

method不是static就会根据new 后面的对象来指向函数.

再往下有待继续学习.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值