본문 바로가기
백엔드

[JAVA] 오버로딩, 오버라이딩

by 작은소행성 2022. 9. 13.

오버로딩

메소드의 이름이 같고 매새변수의 개수나 타입이 다름 

class OverloadingTest {

	public static void main(String[] args) {
		OverloadingMethods om = new OverloadingMethods();

		om.print();
		System.out.println(om.print(3));
		om.print("Hello!");
		System.out.println(om.print(4, 5));
	}
}

class OverloadingMethods {
	public void print() {
		System.out.println("오버로딩1");
	}

	String print(Integer a) {
		System.out.println("오버로딩2");
		return a.toString();
	}

	void print(String a) {
		System.out.println("오버로딩3");
		System.out.println(a);
	}

	String print(Integer a, Integer b) {
		System.out.println("오버로딩4");
		return a.toString() + b.toString();
	}

}

 

 

오버라이딩

부모 클래스로부터 상속 받은 메소드를 자식 클래스에서 재정의 

오버라이딩 하고자 하는 메소드의 이름, 매새변수, 리턴 값이 모두 같아야 함

 

public class OverridingTest {

	public static void main(String[] args) {
		Person person = new Person();
		Child child = new Child();
		Senior senior = new Senior();
		
		person.cry();
		child.cry();
		senior.cry();
	}
}

class Person {
	void cry() {
		System.out.println("흑흑");
	}
}

class Child extends Person {
	@Override
	protected void cry() {
		System.out.println("잉잉");
	}
}

class Senior extends Person {
	@Override
	public void cry() {
		System.out.println("훌쩍훌쩍");
	}
}

 

반응형

'백엔드' 카테고리의 다른 글

[자료구조] B-Tree, B+Tree  (0) 2023.08.20
[웨비나] Bootiful Spring in Summer with Josh Long  (0) 2023.06.26
웹호스팅 / 서버호스팅 / 클라우드 차이점  (0) 2022.07.14
PHP , JAVA 장단점  (0) 2022.07.14
구독 서비스  (0) 2022.07.13