java中静态变量和静态方法的在多态时会有所不同 (本文中代码注释是重点)

/**

*仔细阅读并查看输出,区分不同

*注意,静态变量及静态方法的引用跟声明变量及方法时所用的类有关,即多态有关。

*声明时用父类进行声明,调用时则会调用父类的静态方法及静态变量;

*声明时用子类进行声明,或对已用父类声明过的引用作强制类型转换,调用时则会调用子类的静态方法及静态变量。

**/
public class Static_ {

static String _var="这是父类的静态变量";
public Static_() {
}
public static void static_method(){
System.out.println("这是父类静态方法的输出!");
}


}
class Static_sub extends Static_{
static String _var="这是父类的静态变量的覆盖变量";
public static void static_method(){
System.out.println("这是父类静态的方法的覆盖输出!");
}
}
class test{
public static void main(String args[]){
//以下是类调用
System.out.println("----以下是类调用:");
Static_.static_method();
Static_sub.static_method();
System.out.println("\n");

Static_ sup=new Static_();
Static_sub sub=new Static_sub();
Static_ sup_sub=new Static_sub();
Static_sub sup_sub2=(Static_sub)sup_sub;
System.out.println("\n");

//以下是变量的输出
System.out.println("----以下是变量的输出:");
System.out.println(sup._var);
System.out.println(sub._var);
System.out.println(sup_sub._var);
System.out.println(sup_sub2._var);
System.out.println("\n");

//以下是方法的输出
System.out.println("----以下是方法的输出:");
sup.static_method();
sub.static_method();
sup_sub.static_method();
sup_sub2.static_method();

}
}

***********************************************************************

---------------------------------------------------

以下为上面程序代码的输出:

---------------------------------------------------

----以下是类调用:
这是父类静态方法的输出!
这是父类静态的方法的覆盖输出!




----以下是变量的输出:
这是父类的静态变量
这是父类的静态变量的覆盖变量
这是父类的静态变量
这是父类的静态变量的覆盖变量


----以下是方法的输出:
这是父类静态方法的输出!
这是父类静态的方法的覆盖输出!
这是父类静态方法的输出!
这是父类静态的方法的覆盖输出!

**************************************************************************
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值