Programing/JAVA

상속 INHERITANCE_Part3

쿠크 2022. 3. 3. 16:54

Object 객체

  • 모든 클래스의 부모 클래스
  • 모든 클래스 참조 가능

instanceof

  • 참조변수가 참조하는 인스턴스 실체 타입 확인
  • true 라는 것은 형변환이 가능
package chapter08.poly;

public class ObjectEx {

    public static void main(String[] args) {

        allObject(new GraphicCard());
        allObject(new Amd());
        allObject(new Nvidia());
        allObject("안녕");

    }

    public static void allObject(Object obj) {

        System.out.println(obj.toString());
        if(obj instanceof GraphicCard) {

            GraphicCard gc = (GraphicCard)obj;
            gc.process();
        }
    }

}

추상클래스

  • 추상화: 클래스간의 공통부분을 뽑아내서 공통의 조상을 만드는 작업
  • 추상메서드를 하나 이상 가지고 있는 클래스
  • 미완성 메서드를 포함하고 있다는 의미
  • 추상클래스의 인스턴스는 생성할 수 없으며 상속을 통해서 자손클래스에 의해서 완성됨
  • 추상클래스 자체로는 클래스 역할을 못하지만 새로운 클래스를 작성하는데 있어 바탕이 되는 조상클래스로서의 중요한 의미를 갖음
  • 추상클래스도 생성자가 있으며, 멤버변수와 메서드도 가질 수 있음
  • 추상메서드를 가지고 있지 않아도 추상클래스로 만들 수 있으며 인스턴스 생성 불가 함
  • 추상메서드로 선언하면 자손클래스에서는 반드시 구현해야 한다(구현을 강제 할 수 있다)

추상메서드

  • 메서드는 선언부 + 구현부로 구성
  • 추상메서드는 선언부만 작성
  • abstract return_type method_name(); // {} 넣지 않음

도형클래스 설계

추상클래스

abstract class Shape {
    String type;
    Shape(String type) {
        this.type = type;
    }
    abstract double area();
    abstract double length();
}

추상클래스 상속 받아 구현 1

class Circle extends Shape{
    int r;
    Circle(int r) {
        super("원");
        this.r = r;
    }
    @Override
    double area() {
        return r * r * Math.PI;
    }
    @Override
    double length() {
        return 2 * r * Math.PI;
    }
    @Override
    public String toString() {
        return "Shape [type=" + type + ", r=" + r + "]";
    }
}

추상클래스 상속 받아 구현 2

class Rectangle extends Shape {
    int width, height;
    Rectangle(int width, int height) {
        super("사각형");
        this.width = width;
        this.height = height;
    }

    @Override
    double area() {
        return width * height;
    }
    @Override
    double length() {
        return 2 * (width + height);
    }
    @Override
    public String toString() {
        return "Shape [type=" + type + ", width=" + width + ", height=" + height+"]";
    }

}

테스트

public class ShapeEx {
    public static void main(String[] args) {
        Shape[] shapes = new Shape[2];
        shapes[0] = new Circle(10);
        shapes[1] = new Rectangle(5,5);
        for(Shape s : shapes) {
            System.out.println(s);
            System.out.println("넓이:"+s.area()+" 둘레:"+s.length());
        }
    }
}

클래스 - 배열 Array 사용

부모 클래스 Animal

package chapter08;

public class Animal {

    String type;
    String name;

    Animal(String type, String name) {
        this.type = type;
        this.name = name;
    }

    void sleep() {
        System.out.println(this.name +"은(는) 잠을 잔다.");
    }
}

자식클래스 Eagle

package chapter08;

public class Eagle extends Animal {

    Eagle(String type, String name) {
        super(type, name);
    }

    void sleep() {
        System.out.println(this.name +"은(는) 하늘에서 잠을 잔다.");
    }


}

자식클래스 Tiger

package chapter08;

public class Tiger extends Animal {

    Tiger(String type, String name) {
        super(type, name);
    }

    void sleep() {
        System.out.println(this.name +"은(는) 산속에서 잠을 잔다.");
    }


}

자식클래스 Lion

package chapter08;

public class Lion extends Animal {

    Lion(String type, String name) {
        super(type, name);
    }

    void sleep() {
        System.out.println(this.name +"은(는) 숲속에서 잠을 잔다.");
    }


}

자식클래스 Shark

package chapter08;

public class Shark extends Animal {

    Shark(String type, String name) {
        super(type, name);
    }

    void sleep() {
        System.out.println(this.name +"은(는) 물속에서 잠을 잔다.");
    }


}

테스트

package chapter08;

public class AnimalMain {

    public static void main(String[] args) {

        Animal[] ani = new Animal[4];

        Animal eagle = new Eagle("조류", "독수리");
        Animal tiger = new Tiger("포유류", "호랑이");
        Animal lion = new Lion("포유류", "사자");
        Animal shark = new Shark("어류", "상어");

        ani[0] = eagle;
        ani[1] = tiger;
        ani[2] = lion;
        ani[3] = shark;

        for (int i=0; i<ani.length; i++) {
            ani[i].sleep();
        }

        System.out.println("=========================");

        for(Animal a : ani) {
            a.sleep();
        }
    }
}

클래스 - ArrayList 사용 1

  • ArrayList 만 사용시 형변화 필요
  • 다양한 자료형의 데이터를 추가 삭제 가능 객체
  • 다양한 자료형은 Object 로 입/출력 됨
  • 메서드를 통해 입/출력 add(), get()
package chapter08;

import java.util.ArrayList;

public class AnimalMain2 {

    public static void main(String[] args) {

        ArrayList ani = new ArrayList();

        Animal eagle = new Eagle("조류", "독수리");
        Animal tiger = new Tiger("포유류", "호랑이");
        Animal lion = new Lion("포유류", "사자");
        Animal shark = new Shark("어류", "상어");

        ani.add(eagle);
        ani.add(tiger);
        ani.add(lion);
        ani.add(shark);

        for (int i=0; i<ani.size(); i++) {
            Animal a = (Animal)ani.get(i);
            a.sleep();
        }

        System.out.println("=========================");

        for(Object o : ani) {
            Animal a = (Animal)o;
            a.sleep();
        }
    }
}

클래스 - ArrayList 사용 2

  • ArrayList 자료타입 지정 : 자동 형변환
package chapter08;

import java.util.ArrayList;

public class AnimalMain2 {

    public static void main(String[] args) {

                // <자료타입지정> : 형변화 불필요
        ArrayList<Animal> ani = new ArrayList<Animal>();

        Animal eagle = new Eagle("조류", "독수리");
        Animal tiger = new Tiger("포유류", "호랑이");
        Animal lion = new Lion("포유류", "사자");
        Animal shark = new Shark("어류", "상어");

        ani.add(eagle);
        ani.add(tiger);
        ani.add(lion);
        ani.add(shark);

        for (int i=0; i<ani.size(); i++) {
            ani.get(i).sleep();;
        }

        System.out.println("=========================");

        for(Animal a : ani) {
            a.sleep();
        }
    }
}