본문 바로가기

카테고리 없음

오버로딩(Overloading) vs 오버라이딩(Overriding)

 

오버로딩은 한 클래스 내에서, 같은 메소드를 매개변수를 바꿔서 여러개 정의하여 사용하는 것, 같은 기능을 하는 애는 이름을 똑같이 줄 수 있다. 

 

오버라이딩은 부모 클래스로부터 상속받은 메소드의 동작 방법을 자식 클래스의 상황에 맞게 변경(재정의)하여 우선적으로 사용하는 것

 

 

오버로딩

void overload(){
  System.out.println("매개변수 0개");
}

void overload(int i, int j){
  System.out.println("매개변수 "+ i + " 그리고 " + j);
}

void overload(double d){
  System.out.println("매개변수 " + d);
}

같은 메소드 명인데, 매개변수 개수나, 타입을 바꿔가면서 따로따로 지정하여 사용 할 수 있다.

 

 

 

 

오버라이딩

 

부모 클래스

public class Car() {
	public String name;
    public int release;
    
    public void print(){
    	System.out.println('차종 : '+ this.name + '출시년도 :' + this.release)
    }
}

 

자식 클래스

public class Mustang extend Car {
	String color;
    
    // 메소드 오버라이딩
    public void print(){
    	System.out.println('차종 : '+ this.name + '출시년도 :' + this.release)
        // 신규 추가
     	System.out.println('색상 : '+ this.color)   
    }