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 官宣新年祝福语简短