728x90
반응형
(22.8.1)
# 25강 다형성과 다형성실습
다영성 개념 - 한 가지의 타입이 여러 가지 형태의 인스턴스를 가질 수 있는 것
다형성의 여러 방법 : 붐 자식간의 형변환
1. 업 캐스팅 - 자식 클래스의 객체가 부모클래스의 참조 변수로 형 변환 되는 것
구조) 부모클래스 변수 = 자식 객체값;
- 동적 바인딩 정의 - 컴파일 시점에선 부모클래스의 필드로 인지하나, 런타임 시점에선 자식클래스의 필드로 호출 할 메서드를 묶는 것
package day25;
public class Day25_1 {
public static void main(String[] args) {
Student st1 = new Student("가길동",20,"게임",3);
st1.info();
//업캐스팅
Human h1 = new Student("나길동",17,"롤하기",5);
h1.info();
}
}
class Human{
String name;
int age;
String hobby;
public Human(String name, int age, String hobby) {
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 studey() {
}
}
2. 다운 캐스팅 - 업 캐스팅 된 부모 클래스의 객체가 자식클래스의 참조 변수로 형 변환
구조) 자식클래스변수 = (자식클래스) 업 캐스팅 된 부모 참조 변수;
- 업캐스팅 된 변수만 가능, 명시적 형 변환
package day25;
public class Day25_2 {
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");
}
}
package day25;
public class Day25_3 {
public static void main(String[] args) {
//업캐스팅
Human h1 = new Student("가길동", 20, "게임",3);
//h1.study();
//다운캐팅
Student s1 = (Student)h1;
s1.study();
}
}
package day25;
class Day25_4 {
public static void main(String[] args) {
Animal lion1 = new Lion();
Animal rabbit1 = new Rabbit();
Animal monkey = new Monkey();
Zookeeper james = new Zookeeper();
james.feed(lion1);
james.feed(rabbit1);
james.feed(monkey);
}
}
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+"에게 먹이주기");
}
}
}
///////매개변수 생성 -> 우클릭 -> source ->Generate Constuctor using Fields !!!
# 26 추상 메서드
- 추상 메서드 - 추상 메서드는 선언 부만 정의하고 구체적인 내용은 비워 놓는 메서드
- 추상메서드가 있는 클래스를 상속받는 자식클래스는 반드시 부모 클래스의 추상 메서드를 구현해야한다.
구조) abstact 리턴타입 메서드명(): - 구현하지 않으므로 {} 생략하고 마무리 한다.
- 추상 클래수 - 추상 클래스는 추상 메서드를 멤버로 갖는 클래스
// 추상클래스는 일반 메서드 필드에 존재 단, 추상메서드를 하나라도 포함, 객체 생성불가
- 목적 - 구현은 자식 클래스가 하도록 메서드의 기능을 비워놓고 싶을 때 사용!
package day26;
public class Day26_1 {
public static void main(String[] args) {
Shape shapes[] = new Shape[3];
//부모 객체배열 요소에 자식 값 넣기 -> 업캐스팅
shapes[0] = new Rect();
shapes[1] = new Circle();
shapes[2] = new Line();
for(int i=0;i<3;i++) {
shapes[i].draw();
}
}
}
abstract class Shape{
abstract void draw();
//그리다가 필요하지만 다른 부분이 필요없을때
}
class Rect extends Shape{
void draw() {
System.out.println("사각형을 그리다.");
}
}
class Circle extends Shape{
void draw() {
System.out.println("원을 그리다.");
}
}
class Line extends Shape{
void draw() {
System.out.println("선을 그리다.");
}
}
package day26;
public class Day26_2 {
public static void main(String[] args) {
Pokemon pokemon = new Pikachu();
System.out.println("미포켓몬은"+pokemon.getName());
pokemon.attack();
pokemon.sound();
pokemon = new Squirtle();
System.out.println("미포켓몬은"+pokemon.getName());
pokemon.attack();
pokemon.sound();
}
}
abstract class Pokemon{
String name;
abstract void attack();
abstract void sound();
public String getName() {
return this.name;
}
}
class Pikachu extends Pokemon{
Pikachu(){
this.name="피카츄";
}
@Override
void attack() {
System.out.println("전기공격");
}
@Override
void sound() {
System.out.println("피카피카");
}
}
class Squirtle extends Pokemon{
Squirtle(){
this.name="꼬부기";
}
@Override
void attack() {
System.out.println("물대포");
}
@Override
void sound() {
System.out.println("꼬북꼬북");
}
}
# 27 인터페이스
- 인터페이스 정의 - 물체들 사이의 상호작용 할 수 있도록 하는 매개 역할
// 클래스 - 설계도, 인터페이스 - 규격
package day27;
public class Day27_1 {
public static void main(String[] args) {
B b=new B();
b.methodA();
b.methodB();
}
}
interface Ainter{
final int x = 10;
final int y = 20; //final 생략 가능
abstract void methodA();
void methodB();//abstact 생략 가능
}
class B implements Ainter{
@Override
public void methodA() {
System.out.println("methodA()");
}
@Override
public void methodB() {
System.out.println("methodB()");
}
}
package day27;
public class Day27_3 {
public static void main(String[] args) {
TourGuide guide = new TourGuide();
guide.leisureSports();
guide.sighseeing();
guide.food();
}
}
interface Providable{
void leisureSports();
void sighseeing();
void food();
}
class KoreaTour implements Providable{
@Override
public void leisureSports() {
System.out.println("한강에서 수상스키 투어");
}
@Override
public void sighseeing() {
System.out.println("경북궁 투어");
}
@Override
public void food() {
System.out.println("전주 비빔밤 투어");
}
}
class TourGuide{
private Providable tour = new KoreaTour();
public void leisureSports() {
tour.leisureSports();
}
public void sighseeing() {
tour.sighseeing();
}
public void food() {
tour.food();
}
}
- 인터페이스 다중 구현
package day27;
public class Day27_33 {
public static void main(String[] args) {
MyCellphone phone1 = new MyCellphone();
Camera phone2 = new MyCellphone();
Call phone3 = new MyCellphone();
Memo phone4 = new MyCellphone();
Clock phone5 = new MyCellphone();
PhoneUser user1=new PhoneUser();
user1.call(phone1);
user1.call(phone2);
user1.call(phone3);
}
}
interface Camera{
void photo();
}
interface Call{
void calling();
}
interface Memo{
void write();
}
interface Clock{
void clock();
}
class MyCellphone implements Camera, Call, Memo, Clock{
@Override
public void clock() {
System.out.println("Clock()");
}
@Override
public void write() {
System.out.println("write()");
}
@Override
public void calling() {
System.out.println("calling()");
}
@Override
public void photo() {
System.out.println("photo()");
}
}
class PhoneUser{
void call(call c)
System.out.println("전화를 걸었습니다");
}
반응형
'Java > Java 인강' 카테고리의 다른 글
Java 인강 필기9 (0) | 2022.10.02 |
---|---|
Java 인강 필기 8 (0) | 2022.10.02 |
Java 인강 필기 6 (0) | 2022.10.02 |
Java 인강 필기 5 (0) | 2022.10.02 |
Java 인강 필기 4 (0) | 2022.10.02 |