Java中方法重载与方法隐藏的区别
方法隐藏 - 当超类和子类包含包括参数在内的相同方法,并且如果它们是静态的,当调用时,超类方法会被子类方法隐藏,这称为方法隐藏。
示例
class Demo{
public static void demoMethod() {
System.out.println("method of super class");
}
}
public class Sample extends Demo{
public static void demoMethod() {
System.out.println("method of sub class");
}
public static void main(String args[] ){
Sample.demoMethod();
}
}
输出
method of sub class
方法重载 - 当一个类包含两个同名但参数不同的方法时,当调用时,JVM 根据方法参数执行此方法,这称为方法重载。
示例
public class Sample{
public static void add(int a, int b){
System.out.println(a+b);
}
public static void add(int a, int b, int c){
System.out.println(a+b+c);
}
public static void main(String args[]){
Sample obj = new Sample();
obj.add(20, 40);
obj.add(40, 50, 60);
}
}
输出
60 150
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP