Today I'll share two concepts that are very important in object-oriented programming. One is overloading and the other is scope, which must be noted when writing programs.
This section introduces a concept similar to multiple inheritance but not quite the same – overriding.
The main method of operation is to write a subclass that extends the main class. All the content variables are not changed, and the only difference is that the return value will be overwritten by the new return value of the subclass.
static int plus(int num1,int num2){ //different type & parameters
return num1 + num2 ;
}
static float plus(float num3,float num4){
return num3 + num4;
}
static int gradecalu(int Agrade,int Bgrade){
return Agrade + Bgrade;
}
static int gradecalu(float Cgrade,float Dgrade){
int total = (int)(Cgrade + Dgrade)
return total;
}
public class void main(String[] args){
int ab,cd;
ab = gradecalu(98,23); //ab = 121
cd = gradecalu(65.4,72.3); //cd = 138(四捨五入)
System.out.println(ab);
System.out.println(cd);
}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
/*
此處不能使用x
*/
Scanner input = new Scanner(System.in);
int x = 0;
/*
此處x為0
*/
x = input.nextInt();
/*
經過鍵入數字x得到新數值
*/
}
}
The following describes the scope of the block code:
public class Main {
public static void main(String[] args) {
// 此處不能使用num
{ // 區塊開頭
// 此處num尚未宣告
int num = 9281155;
// 此處可以使用num
System.out.println(num);
} // 區塊結束
// 因為位於區塊外,超出num範圍,不可以使用。
}
}