반응형

오버로딩(Overloading) - 같은 이름의 메서드를 중복하여 정의하는 것

한 클래스 내에서 같은 이름의 메서드를 두개 이상 가질 수 없으나 매개변수의 개수, 타입을 다르게하여 하나의 이름으로 메서드를 작성할 수 있다.

 

인 자바 컴파일러 : https://www.browxy.com/

 - 소스코드

package domain;

public class HelloWorld {

    public static void main(String[] args) {
        OverLoadingTest olt = new OverLoadingTest();
        
        System.out.println(olt.test());
        System.out.println(olt.test("A", "B"));
        System.out.println(olt.test("A", 10, 1234, false));
    }

}

class OverLoadingTest{
    String test(){
        return "매개변수 없음";
    }
    String test(String a, String b){
        return "매개변수 "+a.getClass().getSimpleName()+" "+a+", "+b.getClass().getSimpleName()+" "+b;
    }
    String test(String a, int b, int c, boolean d){
        return "매개변수 "+a.getClass().getSimpleName()+" "+a+", "+((Object)b).getClass().getSimpleName()+" "+b+", "+((Object)c).getClass().getSimpleName()+" "+c+", "+((Object)d).getClass().getSimpleName()+" "+d;
    }
}

 - 결과

매개변수 없음
매개변수 String A, String B
매개변수 String A, Integer 10, Integer 1234, Boolean false

 


오버라이딩(Overriding) - 상속받은 부모 클래스의 메서드를 자식 클래스에서 재정의하는 것

 - 소스코드

package domain;

public class HelloWorld {

    public static void main(String[] args) {
        OverRidingTest ort = new OverRidingTest();
        
        ort.str = "test";
        ort.num = 100;
        ort.bool = true;
        ort.test();
    }

}

class OverRidingTest extends Parent{
    public int num;
    public boolean bool;
    
    public void test(){
        super.test();
        System.out.println("자식 클래스의 변수 : " + ((Object)num).getClass().getSimpleName() +" "+ num +", "+ ((Object)bool).getClass().getSimpleName() +" "+ bool);
    }
}

class Parent{
    public String str;
    
    public void test(){
        System.out.println("부모 클래스의 변수 : " + str.getClass().getSimpleName() +" "+ str);
    }
}

 - 결과

부모 클래스의 변수 : String test
자식 클래스의 변수 : Integer 100, Boolean true
반응형

+ Recent posts