- 오버로딩, 오버라이딩2024년 07월 15일
- chantleman
- 작성자
- 2024.07.15.오전11:06
오버로딩: 파라미터값에 따라 호출되는 메소드, 생성자가 다름
메서드 이름은 같고 매개변수의 유형과 개수가 다름
오버라이딩: 상위(부모) 클래스가 갖고있는 메서드를 하위(자식) 클래스가 재정의해서 사용 (extends 키워드)
오버로딩 예제
public class Student { String nation; String roomNo; String name; int age; public Student(String name, int age) { nation = "한국"; roomNo = "401호"; this.name=name; this.age=age; } public Student(String roomNo, String name, int age) { nation = "한국"; this.roomNo = roomNo; this.name=name; this.age=age; } public static void main(String[] args) { Student st=new Student("홍길동",25); System.out.println(st.nation + st.roomNo + st.name + st.age); Student st1=new Student("402호", "강감찬", 30); System.out.println(st.nation + st1.roomNo + st1.name + st1.age); } }
Student로 같은 이름의 메소드이지만, 안의 파라미터값이 다르다는 것을 확인할 수 있습니다.
오버라이딩 예제
<SuperObject.java> 부모클래스
public class SuperObject { int field1; public void method1() { System.out.println("부모 메소드"); } }
<ExtendObject.java> 자식클래스
public class ExtendObject extends SuperObject{ public static void main(String[] args) { ExtendObject eo = new ExtendObject(); eo.field1 = 10; eo.method1(); System.out.println(eo); } @Override public void method1() { //super : 부모 클래스를 의미함 System.out.println("자식 메소드"); } }
이렇게 'extends 부모클래스'를 적으면 상속을 받고있다는 뜻입니다.
method1을 호출하면
부모 클래스의 메소드가 출력되지만
override를 통해서 method1을 자식 클래스에서 다시 재정의해서 만들면
재정의된 메소드가 출력이 됩니다.
참고로 부모 클래스에 있던 메소드 그대로 출력하고싶다면 super.method1();라고 하면 됩니다.
728x90'cs' 카테고리의 다른 글
CORS (Cross-Origin Resource Sharing), SOP (Same-Origin Policy) (1) 2024.11.26 Web server , WAS (0) 2024.10.15 cpu, 코어, 프로세스, 스레드, 스케줄링 (1) 2024.08.06 프로그래밍 공통 1 (0) 2024.07.17 다음글이전글이전 글이 없습니다.댓글
스킨 업데이트 안내
현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)