상속
기존 클래스를 확장하는 개념으로 부모 클래스를 자식 클래스가 물려받는다.
-활용-
- 코드 중복 방지
- 클래스의 확장을 가능케 한다.
- 부모 클래스의 변경사항을 모든 자식 클래스에 반영시킬 수 있다.
- extends 부모 클래스 형태로 상속을 한다
public class A {
// 부모 클래스
int width = 1;
void triangle() {
System.out.println("triangle");
}
}
public class B extends A{
// extends를 사용해서 상속을 한다
// 자식 클래스
int rectangle;
void info() {
// 부모 클래스의 width값을 가져올 수 있다.
System.out.println(width);
}
}
상속을 통한 간단한 예제
//부모 객체
public class Novice {
private String name;
private int hp;
private int speed;
public Novice() {
// TODO Auto-generated constructor stub
}
public Novice(String name, int hp) {
super();
this.name = name;
this.hp = hp;
}
public void punch(Knight n) {
// TODO Auto-generated method stub
}
public void move() {
System.out.println(speed + "만큼 이동");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
}
//자식 객체
public class Wizard extends Novice{
private int mp;
public Wizard() {
// TODO Auto-generated constructor stub
}
public Wizard(String name, int hp, int mp, int speed) {
super.setHp(hp);
super.setName(name);
super.setSpeed(speed);
this.mp = mp;
}
@Override
public void punch(Knight n) {
// TODO Auto-generated method stub
System.out.println("마법사의 주먹으로 치기");
n.setHp(n.getHp() - 1);
}
public void fireball(Knight n) {
System.out.println("파이어볼~~~");
n.setHp(n.getHp() - 5);
this.mp -= 5;
}
public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp;
}
}
//자식 객체
public class Knight extends Novice{
private int stamina;
public Knight() {
// TODO Auto-generated constructor stub
}
public Knight(String name, int hp,int stamina, int speed) {
super.setHp(hp);
super.setName(name);
super.setSpeed(speed);
this.stamina = stamina;
}
public void punch(Wizard w) {
// TODO Auto-generated method stub
System.out.println("기사의 주먹으로 치기");
w.setHp(w.getHp() - 1);
}
public void slash(Wizard w) {
System.out.println("베기~~~");
w.setHp(w.getHp() - 5);
this.stamina -= 10;
}
public int getStamina() {
return stamina;
}
public void setStamina(int stamina) {
this.stamina = stamina;
}
}
상속 관계에서 자식 객체가 만들어지려면 부모 영역이 먼저 완성되어야 한다.
자식의 생성자 함수에서 super()키워드가 없어도 자동 삽입으로 부모 클래스의 생성자 함수가 호출된다.
- super를 통해 매개변수를 넘겨줄 수 가 있다 혹은 오버로딩을 해줘야 한다.
class Parent{
int width;
public Parent() {
System.out.println("부모 생성자 먼저 호출!!!");
}
public Parent(String text) {
System.out.println("부모의 매개변수 호출 : " + text);
}
}
class Child extends Parent{
public Child() {
super("hello"); //super를 매개변수를 넘겨줘서 부모의 해당하는 생성자가 호출된다. 없으면 기본 생성자 호출
System.out.println("자식 생성자 호출!!!");
}
}
public class Inheritance {
public static void main(String[] args) {
Child child = new Child();
}
}
'JAVA > JAVA' 카테고리의 다른 글
[JAVA] this, super (2) | 2023.12.22 |
---|---|
[JAVA] 추상 클래스 (0) | 2023.12.22 |
[JAVA] 접근 제한자 (0) | 2023.12.20 |
[JAVA] static (0) | 2023.12.20 |
[JAVA] 객체 지향 프로그래밍 (0) | 2023.12.19 |