方法重载和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
热门推荐
10 园长送蛋糕祝福语简短
11 可爱表姐生日祝福语简短
12 老人亲人团聚祝福语简短
13 妹妹生日祝福语幽默简短
14 兄妹过生日祝福语简短
15 新婚祝福语说说大全简短
16 出海霸气祝福语大全简短
17 女职工生日祝福语简短
18 生日祝福语女神 简短独特