黑马程序员技术交流社区
标题:
请大虾帮忙!!关于方法继承问题
[打印本页]
作者:
创出一片辉煌
时间:
2012-7-30 23:47
标题:
请大虾帮忙!!关于方法继承问题
我有点不明白 先看代码吧
class frather{
public static void fun1(){
System.out.println("fun1()");
}
public void fun2(){
System.out.println("fun2()");
}
final static void fun3(){
System.out.println("fun3()");
}
final void fun4(){
System.out.println("fun4()");
}
}
public class extendstatic extends frather{
public static void main(String args[]){
fun1();
fun3();
extendstatic e=new extendstatic();
e.fun2();
e.fun4();
}
/**
public static void fun1(){
System.out.println(" son fun1()");
}**/
}
这个编译成功 成功执行并输出
static 方法可以被继承吗?都说static方法不能被覆写,但是我在子类中也写了一个跟父类中的static方法一样的方法,仍然可以执行,我理解是这样的:
在子类中定义的和父类中一样的static 方法并不是覆写 而是碰巧和父类中static 方法重名而已,但是父类中的static会被子类继承吗?
final方法是不能被覆写的,它可以被继承
如何让一个父类的方法不被子类继承呢?private修饰的除外
作者:
金龙
时间:
2012-7-31 00:02
呃,哥们,首先静态方法这边我觉得你理解的有点不清晰,静态方法是可以被继承的,子类也可以调用父类的静态就足以说明。
静态方法也可以被覆盖,前提是,覆盖它的方法也必须的静态的,即静态只能覆盖静态。
想要父类方法不被子类继承,除了private应该没别的方法了吧,至少我是不知道的
作者:
于星星
时间:
2012-7-31 00:13
子类除了继承父类的方法外,当然可以随意添加自己的方法。所以编译器是不会报错的。但自己添加的静态方法
不能覆盖父类的静态方法。这种不能覆盖是指下面这种情况: frather f = new extendstatic (); f.fun1(); 在非
静态方法中,此时会调用子类的fun1()方法,但由于是静态方法,子类的fun1()方法不会覆盖父类的fun1()方法。
如下图:file:///C:/Documents%20and%20Settings/Administrator/Application%20Data/Tencent/Users/893434467/QQ/WinTemp/RichOle/QQO%7B%255P451K7OGZLMVTXP]X.jpg
下面是引用内容:
子类中的静态方法不会覆盖父类中的同名的静态方法:
public class Parents {
public static void staticMathod(){
System.out.println("parent's static");
}
public void nonStaticMathod(){
System.out.println("parent's nonstatic");
}
}
public class Childs extends Parents{
public static void staticMathod(){
System.out.println("child's static");
}
public void nonStaticMathod(){
System.out.println("child's nonstatic");
}
public static void main(String[] str){
Parents parent1=new Childs();
parent1.staticMathod();
parent1.nonStaticMathod();
}
}
输出结果:
parent's static
child's nonstatic
parent1 是Childs()对象的应用,本因输出
child's static
child's nonstatic
可见子
类没有覆盖父类的方法,子类无法对父类的静态方法进行扩展。
主要原因:1)它是按"编译时期的类型"进行调用的,而不是按"运行时期的类型"进行调用的. 2)而非static方法,才是按"运行时期的类型"进行调用的.
25.jpg
(20.63 KB, 下载次数: 61)
下载附件
2012-7-31 00:13 上传
作者:
戚题彪
时间:
2012-7-31 00:21
静态方法可以被继承,但是不可以被覆盖,子类中定义了一个fun1()只是实现了另一个静态方法,而不是覆盖,在子类中再覆盖一下fun2(),并且再fun1()和fun2()前面都加上@Override注解就知道了,这样fun1()会报错,表示fun1()并不是Override。貌似没有其他方法杜绝方法继承了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2