Java中的方法隐藏和方法重写之间有什么区别?
当超类和子类包含相同的实例方法(包括参数)时,调用时,超类方法将被子类的方法覆盖。
在此示例中,超类和子类具有具有相同签名(方法名称和参数)的方法,当我们尝试从子类中调用此方法时,子类方法将覆盖超类中的方法并得到执行。
示例
class Super{
public void sample(){
System.out.println("Method of the Super class");
}
}
public class MethodOverriding extends Super {
public void sample(){
System.out.println("Method of the Sub class");
}
public static void main(String args[]){
MethodOverriding obj = new MethodOverriding();
obj.sample();
}
}输出结果
Method of the Sub class
当超类和子类包含相同的方法(包括参数)时,如果它们是静态的,则在调用时,超类方法被子类的方法隐藏。
示例
class Super{
public static void sample(){
System.out.println("Method of the Super class");
}
}
public class MethodHiding extends Super {
public static void sample(){
System.out.println("Method of the Sub class");
}
public static void main(String args[]){
MethodHiding obj = new MethodHiding();
obj.sample();
}
}输出结果
Method of the Sub class
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短