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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP