#상속
: 기존의 클래스를 재활용하여 기능을 추가하거나 재정의한 새로운 클래스를 작성하는 것을 의미한다.
- 상위 클래스의 멤버를 하위 클래스와 공유할 수 있다.
- 하위 클래스의 멤버 개수는 항상 상속받은 상위 클래스의 멤버 개수 이상이다.
- 상속 받는 것을 상위 클래스로부터 '확장'되었다고 말하기도 한다.
- 상속의 특징
▪ 다형적 표현이 가능하다. (한 객체가 다양하게 표현될 수 있는 정도)
▪ 상위 클래스의 속성과 기능을 하위 클래스에서 사용할 수 있다.
▪ 자바에서는 단일 상속만 허용된다.
class Scoccer {
String name;
int age;
void pass(){
System.out.println("패스를 합니다.");
};
void shoot(){
System.out.println("슛을 합니다.");
};
void defense()}
System.out.println("수비를 합니다.");
};
}
class Foward extends Soccer { // Soccer 클래스로부터 확장
String teamname;
void score(){
Ststem.out.println("골을 넣습니다.");
};
}
class Midfielder extends Soccer {
String teamname;
void dribble(){
System.out.println("드리블을 합니다."};
};
}
class Defender extends Soccer {
String teamname;
void tackle(){
System.out.println("태클을 합니다.");
};
}
public class Pilgrim {
public static void main(String[] args {
Forward a = new Forward();
a.name = "손흥민";
a.age = 31;
System.out.println(a.name);
a.shoot();
a.score();
Midfielder b = new Midfielder();
b.name = "이강인";
b.age = 22;
System.out.println(b.name);
b.dribble;
b.pass;
Defender c = new Defender();
c.name = "김민재";
c.age = 26;
System.out.println(c.name);
c.defense;
c.tackle;
}
}
//출력값
손흥민
슛을 합니다.
골을 넣습니다.
이강인
드리블을 합니다.
패스를 합니다.
김민재
수비를 합니다.
태클을 합니다.
#포함관계
public class Soccerteam {
int id;
String name;
Address hometown;
public SoccerTeam(int id, String name, Address address) {
this.id = id;
this.name = name;
this.hometown = address;
}
void showInfo() {
System.out.println(name);
System.out.println(address.city+ " " + address.country);
}
public static void main(String[] args) {
Address address1 = new Address("런던", "영국");
Address address2 = new Address("뮌헨", "독일");
SoccerTeam st1 = new SoccerTeam(1, "토트넘 홋스퍼", address1);
SoccerTeam st2 = new SoccerTeam(2, "바이에른 뮌헨", address2);
st1.showInfo();
st2.showInfo();
}
}
class Address {
String city, country;
public Address(String city, String country) {
this.city = city;
this.country = country;
}
}
//출력값
토트넘 홋스퍼
런던 영국
바이에른 뮌헨
뮌헨 독일
- 축구팀의 연고지를 Soccerteam 클래스의 변수가 아닌,
Address 클래스에서 변수를 선언한 뒤, Soccerteam클래스에서 참조변수를 선언하였다.
- 위의 코드에서 Soccerteam 클래스는 Address 클래스를 포함하고 있다.
- 코드의 중복을 없애고 포함관계를 사용한 방법이다.
'개발지 > Today I learn' 카테고리의 다른 글
[0727] 자바 객체지향 프로그래밍 심화 (캡슐화) (0) | 2023.07.27 |
---|---|
[0721] 자바 객체지향 프로그래밍 심화 (상속2) (0) | 2023.07.22 |
[0719] 자바 객체지향프로그래밍 2 (생성자, 내부클래스) (0) | 2023.07.20 |
[0718] 자바 객체지향프로그래밍 2 (필드와 메서드) (0) | 2023.07.19 |
[0717] 자바 객체지향프로그래밍 1 (클래스와 객체) (0) | 2023.07.17 |