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 小红书生日祝福语简短