您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java中的静态方法可以被继承么

2025/11/15 21:47:12发布23次查看
结论:java中静态属性和静态方法可以被继承,但是没有被重写(overwrite)而是被隐藏。
原因:
1、静态方法和属性是属于类的,调用的时候直接通过类名.方法名完成,不需要继承机制便可以调用。
如果子类里面定义了静态方法和属性,那么这时候父类的静态方法或属性称之为隐藏。如果你想要调用父类的静态方法和属性,直接通过父类名.方法或变量名完成,至于是否继承一说,子类是有继承静态方法和属性,但是跟实例方法和属性不太一样,存在隐藏的这种情况。
2、多态之所以能够实现依赖于继承、接口和重写、重载(继承和重写最为关键)。有了继承和重写就可以实现父类的引用指向不同子类的对象。
重写的功能是:重写后子类的优先级要高于父类的优先级,但是“隐藏”是没有这个优先级之分的。
示例如下:
package com.study.test;public class a { //父类 public static string staticstr = "a静态属性"; public string nonstaticstr = "a非静态属性"; public static void staticmethod(){ system.out.println("a静态方法"); } public void nonstaticmethod(){ system.out.println("a非静态方法"); }}
package com.study.test;public class b extends a{//子类b public static string staticstr = "b改写后的静态属性"; public string nonstaticstr = "b改写后的非静态属性"; public static void staticmethod(){ system.out.println("b改写后的静态方法"); }}
package com.study.test;public class c extends a{//子类c继承a中的所有属性和方法}
package com.study.test;public class staticextendstest { public static void main(string[] args) { c c = new c(); system.out.println(c.nonstaticstr); system.out.println(c.staticstr); c.staticmethod();//输出的结果都是父类中的非静态属性、静态属性和静态方法,推出静态属性和静态方法可以 被继承 system.out.println("-------------------------------"); a c1 = new c(); system.out.println(c1.nonstaticstr); system.out.println(c1.staticstr); c1.staticmethod();//结果同上,输出的结果都是父类中的非静态属性、静态属性和静态方法,推出静态属性和 静态方法可以被继承 system.out.println("-------------------------------"); b b = new b(); system.out.println(b.nonstaticstr); system.out.println(b.staticstr); b.staticmethod(); system.out.println("-------------------------------"); a b1 = new b(); system.out.println(b1.nonstaticstr); system.out.println(b1.staticstr); b1.staticmethod();//结果都是父类的静态方法,说明静态方法不可以被重写,不能实现多态 }}
推荐教程:java快速入门
以上就是java中的静态方法可以被继承么的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product