2019-07-05 13:20:34 1476浏览
今天千锋扣丁学堂Java培训老师给大家分享一篇关于static变量能继承吗的详细介绍,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,下面我们一起来看一下吧。
//父类
package com.xujingyang.test;
public class Father {
public static String staticString="父类中的静态变量";
public String str="父类中的非静态变量";
public static void staticMethod(){
System.out.println("父类中的静态方法");
}
public void nostaticMethod() {
System.out.println("父类中的非静态方法");
}
}
//子类
package com.xujingyang.test;
public class Son extends Father {
public static String staticString="子类中的静态变量";
public String str="子类中的非静态变量";
public static void staticMethod(){
System.out.println("子类中的静态方法");
}
public void nostaticMethod() {
System.out.println("子类中的非静态方法");
}
}
//子类
package com.xujingyang.test;
public class A extends Father{
}
//测试方法
package com.xujingyang.test;
public class Test {
public static void main(String[] args) {
Son son=new Son();
System.out.println(son.str);
System.out.println(son.staticString);
son.staticMethod();
son.nostaticMethod();
System.out.println("==============================");
Father f=new Son();
System.out.println(f.str);
System.out.println(f.staticString);
f.staticMethod();
f.nostaticMethod();
System.out.println("==============================");
A f2=new A();
System.out.println(f2.str);
System.out.println(f2.staticString);
f2.staticMethod();
f2.nostaticMethod();
}
}
结果如下:
我发现,变量时无法形成多态的,网上别人说,子类把父类的变量继承过来,内存中会存在两个同名的变量,父类的变量会出现在子类变量之前.如下图:
【关注微信公众号获取更多学习资料】 【扫码进入JavaEE/微服务VIP免费公开课】