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 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语