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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP