iT邦幫忙

2022 iThome 鐵人賽

DAY 13
0
自我挑戰組

30天Java由淺入深系列 第 13

Day 13 : Overloading and Scope

  • 分享至 

  • xImage
  •  

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

  }
}

上一篇
Day 12 : Parameters and Arguments
下一篇
Day 14 : Recursion and Halting Condition
系列文
30天Java由淺入深30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言