풀스택/java
자바_ 부모자식 클래스 상속 ~ 다형성까지
lsme
2022. 4. 14. 19:49
부모 클래스 : Person2
자식 클래스 : President, Student, Employee1
위에 클래스를 응용하는 메인 클래스 : CastingTest
<부모 클래스>
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Person2 {
String name;
int age;
String addr;
int x = 10;
void showSleepingStyle() {
System.out.println("일반사람들의 수면 스타일은 다양하다.");
}
}
|
cs |
<자식 클래스>
1
2
3
4
5
6
7
8
9
10
|
public class President extends Person2{
String nation;
int salary;
@Override //show+ ctrl space
void showSleepingStyle() {
// TODO Auto-generated method stub
System.out.println("대통령은 과도한 업무로 항상 수면시간이 부족하다.");
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class Student extends Person2{
String schoolKind;
int grade;
@Override
void showSleepingStyle() {
// TODO Auto-generated method stub
System.out.println("학생들의 수면스타일은 규칙적이다.");
}
//부모클래스에 정의되어있지않고 자식클래스에만 정의된 메소드
public void study() {
System.out.println("공부를 한다.");
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
|
public class Employee1 extends Person2 {
String department;
int x =30;
@Override
void showSleepingStyle() {
// TODO Auto-generated method stub
System.out.println("직장인은 잦은 회식으로 수면시간이 부족하다.");
}
}
|
cs |
<메인클래스>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
public class CastingTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
President president1 = new President();
//1. 자식클래스 타입의 객체(객체를 가리키는 레퍼런드 값)를
//부모클래스 타입의 레퍼런스 변수에 할당하면
Person2 person2 = president1;
//2. 부모 클래스 타입의 객체(객체를 가리키는 레퍼런드 값)를
//자식클래스 타입의 레퍼런스 변수에 할당하면
//President president2 = person2; //컴파일 오류남.
//명시적인 캐스팅(down)이 필요하다.
if(person2 instanceof President) {
President president2 = (President)person2;
}
//President president2 = (President)person2;
//3. 자바에서는 부모타입의 레퍼런스 변수가 자식클래스객체를 참조할 수 있지만
//자식 클래스 타입의 레퍼런스 변수가 부모객체를 참조할 수는 없다.
Person2 person3 = new Person2();
if(person2 instanceof President) {
President president3 = (President)person2;
}
else {
System.out.println("캐스팅 불가.");
}
//다운캐스팅을 할때는 다운캐스팅을 할 수 있는 지를 판단해야한다.
//이때 사용되는 연산자가 instanceof
//4.자바에서 캐스팅을 부모클래스와 자식클래스 간에서만 가능하다.
Student student1 = new Student();
//President president4 = (President)student1;
//5. 부모 클래스에는 정의되지 않고 자식클래스에만 정의된 메소드는 부모클래스를 통해서 호출할 수 없다.
Person2 person4 = new Student();
//person4.study(); //이럴 경우에 다운 메서드를 사용해야한다.
Student student2 = (Student)person4;
student2.study(); //"공부를 한다."
//6. 부모 클래스에 정의된 클래스를 자식클래스에서 오버라이딩 했을때
// 부모 클래스 타입의 레퍼런스 변수로 해당 메소드를 호출하면 항상 해당 객체에 오버라이딩된 객체가 출력된다.
// 즉, 메소드의 다형성이 제공된다.
Person2 person5 = new Student();
person5.showSleepingStyle();
person5 = new President();
person5.showSleepingStyle();
person5 = new Employee1();
person5.showSleepingStyle();
//7. 변수
//자바에서 호출되는 변수는 컴파일 타입에 결정됨.
//즉, 레퍼런스 변수 타입에 정의된 변수가 호출됨.
Person2 person6 = new Employee1();
System.out.println("person6.x = " + person6.x );
Employee1 employee1 = (Employee1)person6;
System.out.println("employell.x = " + employee1.x);
}
}
|
cs |
<결과값>
위에서 메인코드를 제외하고 나머지 코드를 이용해서
다형성에 대해서 배우기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
//다형성
//요구사항
//만약 사람중에 학생이면 study() 메소드를 호출하라. (instansof)
class PersonInfo {
void printSleepingStyle(Person2 person) {
if(person instanceof Student) {
Student student = (Student)person;
student.study();
}
person.showSleepingStyle();
}
}
public class ParameterPloyTest1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
PersonInfo personInfo = new PersonInfo();
personInfo.printSleepingStyle(new Student());
personInfo.printSleepingStyle(new President());
personInfo.printSleepingStyle(new Employee1());
}
}
|
cs |
<결과값>
<다형성 응용 코드>
가전제품 구매 관련
- 가전 부모 클래스 아래에 가전제품 자식 클래스 만들기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
//가전제품 구매
class Gajun{
@Override
public String toString() {
// TODO Auto-generated method stub
return "Gajun";
}
}
class Tv extends Gajun{
@Override
public java.lang.String toString() {
// TODO Auto-generated method stub
return "Tv";
}
}
class Computer extends Gajun{
@Override
public java.lang.String toString() {
// TODO Auto-generated method stub
return "Computer";
}
}
class dryir extends Gajun{
@Override
public java.lang.String toString() {
// TODO Auto-generated method stub
return "dryir";
}
}
class Buyer{
//현재까지 주문한 목록을 보여줘라.
Gajun[] gajunArray = new Gajun[3];
int index = 0;
void order(Gajun gajun) {
gajunArray[index++] =gajun;
System.out.println(gajun + "를 주문했습니다.");
}
void showOrderList() {
String orderItem = "";
for (int i = 0; i < gajunArray.length; i++) {
orderItem += (i == 0)? gajunArray[i] : "," +gajunArray[i];
}
System.out.println("주문목록 : " + orderItem);
}
}
public class ParameterPloyTest2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Buyer buyer = new Buyer();
buyer.order(new Tv());
buyer.order(new Computer());
buyer.order(new dryir());
buyer.showOrderList();
}
}
|
cs |
<출력결과>