본문 바로가기
CS/개발자필수지식

[CS] 오버로딩과 오버라이딩

by Johnny's 2023. 8. 26.

오버로딩과 오버라이딩

오버로딩(Overloading)

오버로딩은 이름이 같아도 매개변수 개수, 타입, 순서를 다르게 해서 같은 이름으로도 여러 개의 함수를 정의할 수 있는 것. 이는 프로그램의 유연성을 높이고 결과적으로 코드를 깔끔하게 하는 효과가 있으며 같은 클래스 내에서 사용

 

ex1)

class Calculator {
	void multiply(int a, int b)	{
	System.out.println("결과는 : "+(a * b) + "입니다.");
    }
	void multiply(int a, int b,int c) { 
    System.out.println("결과는 : "+(a * b * c) + "입니다.");
	}
	void multiply(double a, double b)	{
	System.out.println("결과는 : "+(a * b) + "입니다."); 
    }
}

public class MyClass {
	public static void main(String args[]) {
   	int a = 1;
	int b = 2;
	int d = 4;
	Calculator c = new Calculator();
   	c.multiply(a, b);
	c.multiply(a, b, d);
	double aa = 1.2;
	double bb = 1.4;
	}
    	c.multiply(aa, bb);
}

//결과는 : 2입니다.
//결과는 : 8입니다.
//결과는 : 1.68입니다.

 

ex2)

class Person {
	void pay(String a, int b) {
	System.out.println(a + "가 "+ b + "원만큼 계산합니다. "); 
    	}
	void pay(int a, String b) {
	System.out.println(b + "가 "+ a + "원만큼 계산합니다. ");    
	} 
}

public class MyClass {
	public static void main(String args[]) {
    Person c = new Person();
    c.pay("영주", 10000000);
    c.pay(10000000, "영주");
	} 
}

//영주가 10000000원만큼 계산합니다. 
//영주가 10000000원만큼 계산합니다.

 

오버라이딩(Overriding)

상위 클래스가 가지고 있는 메서드를 하위 클래스가 재정의를 하는 것. 상속 관계 클래스에서 사용되며 static, final 로 선언한 메서드는 오버라이딩이 불가능

 

ex1)

class Animal { 
    void eat() {
    System.out.println("먹습니다."); 
    }
}

class Person extends Animal {
    @Override
    void eat() {
    System.out.println("사람처럼 먹습니다. ");
    } 
}

public class MyClass {
    public static void main(String args[]) {
    erson a = new Person();
    a.eat();
    } 
}

 

ex2)

interface Animal {
    public void eat(); //static 선언하면 오버라이딩 되지 않음
}

class Person implements Animal {
    @Override
    public void eat() { //재정의
        System.out.println("사람처럼 먹습니다. ");
    } 
}

public class MyClass {
    public static void main(String args[]) {    
        Person a = new Person();
        a.eat();
    } 
}

  

* 참고

- CS 지식의 정석 | 디자인패턴 네트워크 운영체제 데이터베이스 자료구조 -인프런

댓글