Backend/JAVA2 멘토시리즈

JAVA Eclipse 25 상속과 다형성 - 다형성 개념과 다형성 관련 실습

쏠솔랄라 2023. 5. 11. 18:39

 

 

다형성

 

: 한 가지의 타입이 여러 가지 형태의 인스턴스를 가질 수 있는 것

 

 

다형성의 여러 가지 방법

부모 자식 간의 형 변환(casting)

 

upcasting

 

 

downcasting

 

 

public : 누구나 접근할 수 잇는

private : 자식이 상속받을 수 없는 필드

default : 같은 패키지 내에서만

protected : 다른패키에서는 자식만 접근할 수 있다

 

 

 

 

upcasting

 

: 자식 클래스의 객체가 부모 클래스의 참조변수로 형 변환 되는 것

 

부모클래스 변수 = 자식 객체값;

 

형변환은 생략 가능해 명시적인 형 변환아 아니어도 가능

 

 

ex1.

public class upcasting {

 

public static void main(String[] args) {

 

Student st1 = new Student("이름", 25, "취미", 2);

st1.info();

st1.study();

 

// 업캐스팅

Human h1 = new Student("업캐스팅", 12, "게임", 5);

h1.info();

// 상속받은 자식클래스를 부모클래스에서 사용할 때 동적바인딩이 일어난다

// 값은 자식 값으로 채우되 공간은 부모의 것이다

 

// h1.study(); 사용불가

// h1.grade(); 사용불가

 

}

}

class Human {

 

String name;

int age;

String hobby;

 

public Human(String name, int age, String hobby) {

super();

this.name = name;

this.age = age;

this.hobby = hobby;

}

 

void info() { //동적, 변수

System.out.println("name: " + name);

System.out.println("age: " + age);

System.out.println("hobby: " + hobby);

}

}

class Student extends Human {

 

int grade;

 

public Student (String name, int age, String hobby, int grade) {

 

super(name, age, hobby);

this.grade=grade;

}

 

void info() { // 오버라이딩

super.info();

System.out.println("grade: " + grade);

}

 

void study () {

System.out.println("공부하기");

}

}

 

 

출력화면

 

 

ex2.

 

public class Polymorphism {

 

public static void main(String[] args) {

A obj = new B(); // 부모의 변수=자식값 ; 업캐스팅

obj.methodA();

// obj.methodB(); 불가

}

}

 

class A {

void methodA () {

System.out.println("methodA");

}

}

 

class B extends A{

void methodB () {

System.out.println("methodB");

}

}

 

 

downcasting

 

: 업캐스팅 된 부모 클래스의 객체가 자식클래스의 참조 변수로 형변환 되는 것

 

자식 클래스 변수 = (자식 클래스) 업캐스팅 된 부모 참조 변수;

 

업캐스팅 된 변수만 가능

명시적인 형 변환만 가능

 

 

ex1.

public class downcasting {

public static void main(String[] args) {

 

// 업캐스팅 된 클래스

Human h1 = new Student("학생", 2, "게임", 3);

 

// 다운캐스팅

Student s1 = (Student)h1;

s1.info();

s1.study();

}

}

 

 

출력화면

 

ex2.

public class Polymorphism2 {

public static void main(String[] args) {

Animal lion1 = new Lion();

Animal rab1 = new Rabbit();

Animal mon1 = new Monkey();

Zookeeper james = new Zookeeper();

 

james.feed(lion1);

james.feed(rab1);

james.feed(mon1);

 

Animal animal = new Animal();

animal.breath();

}

}

 

class Animal {

void breath () {

System.out.println("숨쉬기");

}

}

 

class Lion extends Animal {

public String toString() {

return "사자";

}

}

 

class Rabbit extends Animal {

public String toString() {

return "토끼";

}

}

 

class Monkey extends Animal {

public String toString() {

return "원숭이";

}

}

 

class Zookeeper {

void feed (Animal animal) {

System.out.println(animal + "에게 먹이주기");

}

}

 

 

출력화면

 

 




JAVA Eclipse 01 프로그램, 프로그래밍, 기계어, JAVA
https://developernew.tistory.com/63

JAVA Eclipse 02 자바 출력메서드와 입력메서드
https://developernew.tistory.com/71

JAVA Eclipse 03 변수, 자료형, 형변환, 변수의 상수화
https://developernew.tistory.com/74

JAVA Eclipse 04 연산자 정의, 연산자 종류, 연산자 우선순위
https://developernew.tistory.com/78

JAVA Eclipse 05 논리연산자, 비트연산자
https://developernew.tistory.com/80

JAVA Eclipse 06 기타연산자 - 삼항연산자, 대입연산자, 복합대입연산자, instanceof
https://developernew.tistory.com/84

JAVA Eclipse 07 제어문 : 조건문
https://developernew.tistory.com/88

JAVA Eclipse 08 제어문 : 조건문 switch + Random 클래스
https://developernew.tistory.com/93

JAVA Eclipse 09 제어문 : 반복문 for
https://developernew.tistory.com/102

JAVA Eclipse 10 제어문 : 반복문 while, do-while
https://developernew.tistory.com/103

JAVA Eclipse 11 제어문 : 반복문의 break, continue
https://developernew.tistory.com/106

JAVA Eclipse 12 배열 : 배열의 개념 및 사용
https://developernew.tistory.com/107

JAVA Eclipse 13 배열 : 예제풀이, 로또번호 생성기
https://developernew.tistory.com/115

JAVA Eclipse 14 배열 : 다차원배열
https://developernew.tistory.com/117

JAVA Eclipse 15 배열의 복제, for ~ each문
https://developernew.tistory.com/120

JAVA Eclipse 16 카페 주문 시스템(키오스크) 배열과 제어문(반복문, 조건문)으로 풀기
https://developernew.tistory.com/124

JAVA Eclipse 17 method 메서드(메소드)
https://developernew.tistory.com/126

JAVA Eclipse 18 메서드(메소드) 오버로딩
https://developernew.tistory.com/133

JAVA Eclipse 19 객체지향 언어
https://developernew.tistory.com/135

JAVA Eclipse 20 클래스와 객체
https://developernew.tistory.com/155

JAVA Eclipse 21 인스턴스 변수와 클래스 변수
https://developernew.tistory.com/156

JAVA Eclipse 22 객체 타입 배열
https://developernew.tistory.com/157

JAVA Eclipse 23 클래스 생성자
https://developernew.tistory.com/158

JAVA Eclipse 24 상속과 다형성 - 상속/메서드 오버라이딩
https://developernew.tistory.com/159