JAV) 0331-1 다형성과 타입 변환

조한미르·2024년 3월 31일
1
  • 타입변환 : 타입을 다른 타입으로 변환
	- 자료형(타입) 변환
    - 클래스의 객체 타입 변환
    
    
  • 클래스의 형변환

    1. 형변환 가능 (강제, 자동)
    2. 상속 관계가 있을때만 가능
    3. 1차 상속 관계가 아니더라도 가능
    4. 자식에서 부모타입으로의 형변환만 가능
    5. 부모타입으로 변환 할 경우 class인 경우는 자식이 속성이나 기능 사용 X
  • 다향성
    : 다향성은 객체지향 프로그래밍의 대표적인 특징중 하나.
    하나의 타입으로 다양한 개체를 사용 할 수 있는 것을 의미.
     

실습)

  • Car

    public class Car {
    
        private String myName;
    
        public Car(String myname) {
            this.myName = myName;
        }
    
        public String getMyName() {
            return this.myName;
        }
    }
  • Bus extends Car

    public class Bus extends Car {
    
        public Bus(String myName) {
            super(myName);
        }
    
        public voif getInfo() {
            System.out.printlnl("버스 이름은 " + this.getMyName() + "입니다.");
        }
    }
  • Taxi extends Bus
    public class Taxi extends Bus {

        public Taxi(String myName) {
            super(myName);
        }

        public voif getInfo() {
            System.out.printlnl("택시 이름은 " + this.getMyName() + "입니다.");
        }
    }
  • TypeTestMain
    public class TypeTestMain {

        public static void main(String[] args) {


            Bus b = new Bus("버스");
            Taxi t1 = new Taxi("개인택시");


            //형변환
            Car car = t1;

            b.getInfo();
            t1.getInfo();

        //부모 타입으로 형변환 되면 자식클래스가 가진 기능이나 속성을 사용 할 수 없다.
        //car.getInfo();


        //강제형변환
        Taxi t2 = (Taxi)car;

        t2.getInfo();


        }
    }
    
    
    
  • 클래스 자동 타입 변환 예제)
  class Car {}

  class Bus extends Car {}

  class SchoolBus extends Bus {}


  class OpenCar extends Car {}
  class SportsCar extends OpenCar {}


  public class EX11_02 {

      public static void main(String[] args) {

          Car = new SchoolBus();    //1차 상속 관계가 아니더라도 자동 타입 변환 가능

          Bus b1 = Bus();            // 자동타입변환 
          Bus b2 = new SchoolBus();  // 자동타입변환


          Car c2 = new OpenCar();     // 자동타입변환
          OpenCar oc = new SportsCar  // 자동타입변환



          //Bus b3 = new OpenCar(); <- 오류!!
  • instance of

    instanceof 연산자를 이용하여 참조 변수가 참조 되고 있는 인스턴스의 실제타입을 확인 가능
  public interface Computer {

      public abstract void powerOn();
      void powerOff();




  --------------------------------------------------------------
  public class SamsungCom implements Computer {

      @Override
      public void powerOn() {

      System.out.println("Hello SamSung!");
      System.out.println("전원이 켜집니다.");

      }

      @override
      public void powerOff() {

      System.out.println("GoodBye SamSung!");
      System.out.println("전원이 꺼집니다.");

      }
  }

  ------------------------------------------------------------
  public class LG implements Computer {

      @Override
      public void powerOn() {

      System.out.println("Hello LG!");
      System.out.println("전원이 켜집니다.");

      }

      @override
      public void powerOff() {

      System.out.println("GoodBye LG!");
      System.out.println("전원이 꺼집니다.");

      }
  }

  ---------------------------------------------------------




  public class ComputerRoom {

      private Computer com1;
      private Computer com2;


      public Computer getCom1() {
          return com1;
      }
      public void setCom1(Computer com1) {
          this.com1 = com1;
      }
      public Computer getCom2() {
          return com2;
      }
      public void setCom2(Computer com2) {
          this.com2 = com2;
      }

      public void allPowerOn() {
          this.com1.powerOn();
          this.com2.powerOn();
      }


      public void allPowerOff() {
          this.com1.powerOff();
          this.com2.powerOff();
      }
  }

  -------------------------------------------------------------------------


  public class CompMain {


      public static void main(String[] args) {

      ComputerRoom room = new ComputerRoom();

      room.setCom1(new LGCom());
      room.setCom2(new SamSungCom());

      room.allPowerOn();
      room.allPowerOff();
      }
  }


  -------------------------------------------------
  전원이 켜집니다.
  Hello SamSung!
  전원이 켜집니다.
  Hello LG!
  전원이 꺼집니다.
  GoodBye SamSung!
  전원이 꺼집니다.
  GoodBye LG!


  ----------------------------------------------------
  publiic class CompareInstance {

      public ststic void getMyType(Computer com) {

          if(com instanceof SamsungCom) {
              System.out.println("삼성 컴퓨터!");
          }else if(com instanceof LGCom) {
              System.out.println("LG 컴퓨터!");
          }else {
              Sytem.out.println("넌누구냐..");

      public static void main(String[] args) {


          Computer sam = new SamSungCom();
          Computer lg = new LGCom();

          CompareInstance.getMyType(sam);
          CompareInstance.getMyType(lg);
      }
  }


  -> 삼성 컴퓨터!
  LG 컴퓨터!

  
profile
꼭 해내는 사람

1개의 댓글

comment-user-thumbnail
2024년 4월 1일

🫶최고🫶

답글 달기