1. 상속
- 객체지향 프로그래밍에서 '상속' 관계란 부모 클래스와 자식 클래스가 주체가 되어 자식클래스가 부모의 변수 및 메서드를 상속받아 활용할 수 있는 것을 말합니다.
- 즉, 부모가 자녀에게 변수/메서드 상속해주게 되면 자식은 부모가 가지고 있는 상태/동작을 모두 활용할 수 있습니다.
- 자바에서 extends 를 활용해 상속받는데, 자녀 클래스는 extends 키워드를 통해 부모 클래스를 상속받습니다.
- 부모 클래스는 상위 클래스(슈퍼 클래스, super class) 라고 하며, 자식 클래스는 하위 클래스(서브 클래스, sub class) 라고 합니다.
상속의 방법은 다음과 같다.
public class 자식클래스명 extends 부모클래스명
public class Manager extends Employee {
}
2. 오버라이딩
오버라이딩(overriding)이란 상속 관계에 있는 부모 클래스에서 이미 정의된 메소드를 자식 클래스에서 같은 시그니쳐를 갖는 메소드로 다시 정의하는 것이라고 할 수 있습니다.
- 자바에서 자식 클래스는 부모 클래스의 private 멤버를 제외한 모든 메소드를 상속받습니다.
- 이렇게 상속받은 메소드는 그대로 사용해도 되고, 필요한 동작을 위해 재정의하여 사용할 수도 있습니다.
- 즉, 메소드 오버라이딩이란 상속받은 부모 클래스의 메소드를 재정의하여 사용하는 것을 의미합니다.
오버라이딩의 방법은 다음과 같습니다.
public class 자식클래스명 extends 부모클래스명
public 리턴타입 메소드명(매개변수1, 매개변수2...){}
public class Manager extends Employee {
public int Id() {
return super.Id() + 100;
}
}
3. 실습예제
Exercise) 아래 Rectangle.java를 상속받은 Box.java에서 area() 메소드를 오버라이딩하여 재정의 하세요
(단, 연산공식은 자유롭게 하셔도 됩니다.)
Rectangle.java
package com.bawp.inheritance;
public class Rectangle {
private int length;
private int width;
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int area() {
return this.getLength() * this.getWidth();
}
}
Box.java
package com.bawp.inheritance;
public class Box extends Rectangle {
private int height;
public Box(int length, int width, int height) {
super(length, width);
this.height = height;
}
//getters and setters
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return this.height;
}
}
Solution)
Box.java
package com.bawp.inheritance;
public class Box extends Rectangle {
private int height;
//MUST have this constructor ( with the super() constructor call )
public Box(int length, int width, int height) {
super(length, width);
this.height = height;
}
//getters and setters
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return this.height;
}
//TODO: override area method
public int area() {
return 2 * (getLength() * getWidth() + getLength() * height + getWidth() * height);
}
}
'Java Study' 카테고리의 다른 글
Java Study(캡슐화) (0) | 2023.04.19 |
---|---|
Java Study(배열/키 값) (0) | 2023.04.04 |
Java Study(생성자/접근제한자) (0) | 2023.03.30 |
Java(class/object) (0) | 2023.03.29 |
Java (method/메소드) (0) | 2023.03.28 |