[Java/자바] Methods, Overriding

sbj·2023년 11월 24일

Java

목록 보기
1/15
post-thumbnail

Learning Objectives (학습목표)

  • Review the basics of Java.
    자바 기초를 복습한다.

Methods (메소드)

public class Main {

	public static void main(String[] args) {
		//method = a block of code that is executed whenever it is called
		String name = "Bro";
		
		for(int i=1; i<name.length();i++) {
			hello(name);
		}		
	}
	static void hello(String name) {
		System.out.println("Hello " + name);
	}
}
  1. method is a block of code which only runs when it is called.
    메소드는 오직 호출될 때만 실행된다.
  2. You can pass data, known as parameters, into a method.
    Data와 파라미터를 메소드에 전달할 수 있다.
  3. Methods are used to perform certain actions, and they are also known as functions.
    메소드는 특정 액션을 수행하는 데 사용되고, ‘함수’로 알려져있다.
  4. Why use methods? To reuse code: define the code once, and use it many times.
    왜 메소드를 사용할까? → 재사용, 메소드를 한 번 정의해두면 many times 사용 가능하다.

Method Overloading (오버로딩)

  1. Multiple methods can have the same name with different parametrs.

Example

package overriding;

public class Main {

	public static void main(String[] args) {

		// overloaded methods = methods that share same name but have different parameters
		// method name + parameters = method signature
		
		int x = add(1,2);
		int y = add(1,2,3);
		int z = add(1,2,3,4);
		System.out.println(x);
		System.out.println(y);
		System.out.println(z);
		
		double x2 = add(1.0, 2.0, 3.0, 4.0);
		System.out.println(x2);
		
	}
	static int add(int a, int b) {
		System.out.println("This is overloaded method #1");
		return a+b;
	}
	static int  add(int a, int b, int c) {
		System.out.println("This is overloaded method #2");
		return a+b+c;
	}	
	static int add(int a, int b, int c, int d){
		System.out.println("This is overloaded method #3");
		return a+b+c+d;
	}
	
	static double add(double a, double b) {
		System.out.println("This is overloaded method #1");
		return a+b;
	}
	static double  add(double a, double b, double c) {
		System.out.println("This is overloaded method #2");
		return a+b+c;
	}	
	static double add(double a, double b, double c, double d){
		System.out.println("This is overloaded method #3");
		return a+b+c+d;
	}
}

Example

Instead of defining two methods that should do the same thing, it’s better to overload one.
두 개의 메소드를 생성하는 것 대신에, 하나를 overload하는 것이 더 적절하다.

In the example below, we overload the plusMethod method to work for both int and double:
하기 코드에선 plusMethod가 int와 double 두 가지 변수에 대해 작동할 수 있다.

public class Main2 {
	public static void main(String[] args) {
		
		int myNum = plusMethod(5,10);
		double myNum2 = plusMethod(5.0,4.0);
		
		System.out.println(myNum + " " + myNum2);
		}
	static int plusMethod(int x, int y) {
		return x + y;
	}
	static double plusMethod(double x, double y) {
		return x + y;
	}
}

profile
Strong men believe in cause and effect.

1개의 댓글

comment-user-thumbnail
2023년 11월 25일

좋은 글 감사합니다.

답글 달기