Day 13 : Overloading and Scope

Chi-Tse Chiang
2022-09-28 23:55:29

Intro

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.

Overloading: Simply put, it means defining functions with the same name in the same class, but with different types of arguments passed in and defined parameters.

Scope: Because Java uses a compiler (and later, due to cross-platform requirements, an interpreter), which means that the code is compiled before being executed, the scope of variables and function definitions is very important.

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.

Overloading

static int plus(int num1,int num2){       //different type & parameters
		return num1 + num2 ;
}
static float plus(float num3,float num4){
		return num3 + num4;
}

Two functions with the same name, we found that their return values and defined parameter types are different. This is called overloading.

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);
}

Program analysis: We can observe why the compiler knows how to correctly reference the function when we call it with the same name?
Because we pass different arguments in, Java knows to call the corresponding function based on the parameter's class.

Scope

We say that the scope of a variable is the area or block of functions in which the variable can be used.

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範圍，不可以使用

  }
}