코드스테이츠 BE 14일차 - Java 다형성, 추상화

coding infant·2022년 7월 12일

코드스테이츠BE

목록 보기
14/48

캡슐화

외부로부터 클래스에 정의도니 속성과 기능을 보호 (데이터 보호)
외부에는 필요한 부분만 노출 (데이터 은닉)
private default protected public 접근자
getter/setter 메서드

접근 제어자

다형성

[학습목표]

자바 객체지향 프로그래밍에서 다형성이 가지는 의미와 장점을 이해할 수 있다.
참조변수의 타입 변환에 대한 내용을 이해하고, 업캐스팅과 다운캐스팅의 차이를 설명할 수 있다.
instanceof 연산자를 언제 어떻게 활용할 수 있는 지 이해하고 설명할 수 있다.
코딩 예제를 실제로 입력해보면서 다형성이 실제로 어떻게 활용되는 지 이해할 수 있다.

다형성 : 하나의 객체가 여러가지 형태를 가질 수 있는 성질
자바에서의 다형성 : 한 타입의 참조변수를 통해 여러 객체를 참조 가능. 상위 클래스 타입의 참조변수를 통해서 하위 클래스의 객체를 참조
(오버로딩 오버라이딩)

Car sportcar = new SportCar(); // 가능
SportCar sportcar = new Car(); // 불가능
내용을 입력하세요.

class Friend {
    public void friendInfo() {
        System.out.println("나는 당신의 친구입니다.");
    }
}
class BoyFriend extends Friend {
    public void friendInfo() {
        System.out.println("나는 당신의 남자친구입니다.");
    }
}
class GirlFriend extends Friend {
    public void friendInfo() {
        System.out.println("나는 당신의 여자친구입니다");
    }
}
public class FriendTest {
    public static void main(String[] args) {
        Friend friend = new Friend();               // 객체 타입과 참조변수 타입의 일치
        BoyFriend boyfriend = new BoyFriend();
        Friend girlfriend = new GirlFriend();       //  객체 타입과 참조변수 타입의 불일치 -> 가능
        // Friend girlfriend1 = new Friend();        -> 하위클래스 타입으로 상위클래스 객체 참조 -> 불가

        friend.friendInfo();
        boyfriend.friendInfo();
        girlfriend.friendInfo();

    }
}

상위 클래스로 하위 클래스 참조 가능
참조변수가 사용할 수 있는 멤버의 개수 : 상위 클래스의 멤버의 수
(하위 클래스로 상위 클래스 참조는 불가. 실제 객체인 Friend 멤버 개수보다 friend1의 멤버 개수 더 많기 때문)

[참조변수의 타입 변환]
① 서로 상속 관계에 있는 상위 클래스 - 하위 클래스 사이 타입 변환
② 하위 클래스 타입 -> 상위 클래스 타입으로의 변환(업캐스팅)은 형변환 연산자(괄호) 생략 가능
③ 상위 클래스 -> 하위 클래스로의 변환(다운캐스팅)은 형변환 연산자(괄호) 반드시 명시

public class VehicleTest {
    public static void main(String[] args) {
        Car car = new Car();
        Vehicle vehicle = (Vehicle) car;        // 상위 클래스 Vehicle 타입으로 변환(생략 가능)
        Car car2 = (Car) vehicle;               // 하위 클래스 Car 타입으로 변환 (생략 불가능)
        MotorBike motorBike = (MotorBike) car;  // 상속관계가 아니므로 타입 변환 불가 -> 에러 발생
    }
}

class Vehicle {
    String model;
    String color;
    int wheels;

    void startEngine() {
        System.out.println("시동 걸기");
    }
    void accelerate() {
        System.out.println("속도 올리기");
    }
    void brake() {
        System.out.println("브레이크!");
    }
}

class Car extends Vehicle {
    void giveRide() {
        System.out.println("다른 사람 태우기");
    }
}
class MotorBike extends  Vehicle {
    void performance() {
        System.out.println("묘기 부리기");
    }
}

[instanceof 연산자]

캐스팅이 가능한지 여부를 boolean 타입으로 확인할 수 있음

(캐스팅 여부 : 객체를 어떤 생성자로 만들었는가, 클래스 사이에 상속관계가 존재하는가)


// 참조변수 instanceof 타입

public class InstanceOfExample {
    public static void main(String[] args) {
        Animal animal = new Animal();
        System.out.println(animal instanceof  Object);      // true
        System.out.println(animal instanceof  Animal);      // true
        System.out.println(animal instanceof  Bat);         // false

        Animal cat = new Cat();
        System.out.println(cat instanceof  Object);         // true
        System.out.println(cat instanceof Animal);          // true
        System.out.println(cat instanceof Cat);             // true
        System.out.println(cat instanceof Bat);             // false
    }
}

class Animal {};
class Bat extends Animal{};
class Cat extends Animal{};

[다형성의 활용 예제]

void buyCoffee(Americano americano) {       // 아메리카노 구입
    money = money - americano.price;
}
void buyCoffee(CaffeLatte caffeLatte) {     // 카페라떼 구입
    money = money - caffeLatte.price;
}

// 또는 

void buyCoffe(Coffee coffee) {              // 매개변수의 다형성
    money = money - coffee.price
}

참고사이트

http://wiki.hash.kr/index.php/%EB%8B%A4%ED%98%95%EC%84%B1

https://ko.wikipedia.org/wiki/%EB%8B%A4%ED%98%95%EC%84%B1_(%EC%BB%B4%ED%93%A8%ED%84%B0_%EA%B3%BC%ED%95%99)

https://www.tutorialspoint.com/java/java_polymorphism.htm

http://www.tcpschool.com/java/java_polymorphism_concept

추상화

[학습 목표]

추상화의 핵심 개념과 목적을 이해하고 설명할 수 있다.
abstract 제어자가 내포하고 있는 의미를 이해하고, 어떻게 사용되는 지 설명할 수 있다.
추상 클래스의 핵심 개념과 기본 문법을 이해할 수 있다.
final 키워드를 이해하고 설명할 수 있다.
자바 추상화에서 핵심적인 역할을 수행하는 인터페이스의 핵심 내용과 그 활용을 이해할 수 있다.
추상 클래스와 인터페이스의 차이를 설명할 수 있다.

[추상화]

기존 클래스의 공통적인 요소 뽑아서 상위 클래스 만드는 것
-> 추상 클래스, 인터페이스 사용

[abstract 제어자]

추상적인, 미완성의


abstract class AbstractExample { // 추상 메서드가 최소 하나 이상 포함되어 있는 추상 클래스
    abstract void start();       // 메서드 바디가 없는 추상 메서드
   

abstract method

abstract class

미완성이기에 객체 생성이 불가능

[추상 클래스]

메서드 시그니처만 존재하고 바디가 선언되지 않은 추상 메서드를 포함하는 '미완성 설계도' -> 객체 생성 불가

상속 관계시 새 클래스 작성하는데 유용 (유연한 대처 가능) -> 오버라이딩 사용

abstract class Animal {
    public String kind;
    public abstract void sound();
}
class Dog extends Animal {                                  // Animal 클래스로부터 상속
    public Dog() {
        this.kind = "포유류";
    }
    public void sound() {                                   // 메서드 오버라이딩 -> 구현부 완성
        System.out.println("멍멍");                         // 멍멍
    }
}

class Cat extends Animal {                                  // Animal 클래스로부터 상속
    public Cat() {
        this.kind = "포유류";
    }
    public void sound() {                                   // 메서드 오버라이딩 -> 구현부 완성
        System.out.println("야옹");                         // 야옹
    }
}
class DogExample {
    public static void main(String[] args) throws Exception {
        Animal dog = new Dog ();
        dog.sound();

        Cat cat = new Cat();
        cat.sound();
    }
}

추상 클래스 사용시 상속 받는 하위클래스에서 오버라이팅 통해 각각 상황 맞는 메서드 구현 가능
상속 계층도 상층부 위치할수록 추상화 정도 높고 아래로 내려갈수록 구체화

[final 키워드]
필드, 지역변수, 클래스 앞에 위치
final 클래스 : 변경 또는 확장 불가능한 클래스, 상속 불가
final 메서드 : 오버라이딩 불가
final 변수 : 값 변경이 불가한 상수

public class FinalEx {              // 확장/상속 불가능한 클래스
    final int x =1;                 // 변경되지 않는 상수
    
    final void getNum() {           // 오버라이딩 불가한 메서드
        final int localVar = x;     // 상수
        return x;
    }
}

[인터페이스]

밑그림
추상 메서드의 집합 (cf : static, default 메서드와 상수 제외)
추상 클래스보다 높은 추상성

추상 클래스는 구현메서드가 포함될 수 있다. 인터페이스는 추상메서드만

여기부터 복습 다시 하기

0개의 댓글