JAVA를 잡아라!...

JAVA_추상클래스_#1_Shape 본문

JAVA/JAVA_복습문제

JAVA_추상클래스_#1_Shape

onivv 2023. 12. 6. 17:04

문제

//모양 클래스 (이름,넓이)
//원 클래스 (반지름)
//사각 클래스 (가로,세로)

main(){
	Shape datas = new Shape[3];
    datas[0] = new Circle();
    datas[1] = new Rect();
    datas[2] = new Circle("도넛");
    
    for(Shape data : datas) {
    	data.printInfo();
    }
}

 

한글코딩

abstract class Shape {
	String 이름;
	double 넓이;
    Shape(String 이름){
    	this.이름 = 이름;
        this.넓이 = 0.0;
    }
    abstract void printInfo();
}

class Circle extends Shape {
	int 반지름;
	double 원주율;
	Circle() {
	}
	Circle(이름) {
	}
	Circle(이름, 원주율) {
	}
	@printInfo()
}

class Rect extends Shape {
	int 가로;
	int 세로;
	Rect() {
	}
	Rect(이름) {
	}
	Rect(이름, 가로, 세로) {
	}
	@printInfo()
}

 

코드

package class01;

abstract class Shape {
	String name;
	double area;
	Shape(String name) {
		this.name = name;	//name속성 강제!
		this.area = 0.0;	//0.0으로 초기화, 가독성 ↑
	}
	abstract void printInfo();
}

class Circle extends Shape {
	int radius;
	final static double PI = 3.14;
	//원주율은 공유자원!, 모든 객체에게 공통적으로 적용
	//객체와 무관하니까 ★static 붙이기
	//변하지 않는 상수값이니까 final도 붙여줌
	
	//[3] 생성자
	Circle() {
		this("원");
	}
	//[2] 생성자 : 이름
	Circle(String name) {
		this(name, 1);
	}
	//[1] 생성자 : 이름, 반지름
	Circle(String name, int radius) {
		super(name);
		this.radius = radius;
		this.area = this.radius * this.radius * Circle.PI;
	}
	@Override
	void printInfo() {
		System.out.print("이름: " + this.name);
		System.out.println(", 반지름: " + this.radius + ", 넓이: " + this.area);
	}
	
}

class Rect extends Shape {
	int x;
	int y;
	//[3] 생성자
	Rect(){
		this("사각");
	}
	//[2] 생성자 : 이름
	Rect(String name) {
		this(name, 1, 1);
	}
	//[1] 생성자 : 이름, 가로, 세로
	Rect(String name, int x, int y) {
		super(name);
		this.x = x;
		this.y = y;
		this.area = this.x * this.y;
	}
	@Override
	void printInfo() {
		System.out.print("이름: " + this.name);
		System.out.println(", 가로: " + this.x + ", 세로: " + this.y + ", 넓이: " + this.area);
	}
}

public class Test01 {

	public static void main(String[] args) {
    	//Shape s = new Shape(); 추상클래스는 객체화 불가!! ★
		Shape[] datas = new Shape[3];
		datas[0] = new Circle("피자", 10);
		datas[1] = new Rect("A4", 10, 30);
		datas[2] = new Circle();
		
		for(Shape data : datas) {
			data.printInfo();
		}
	}
}

 

출력

이름: 피자, 반지름: 10, 넓이: 314.0
이름: A4, 가로: 10, 세로: 30, 넓이: 300.0
이름: 원, 반지름: 1, 넓이: 3.14

'JAVA > JAVA_복습문제' 카테고리의 다른 글

JAVA_인터페이스_#1_TV (+ 싱글톤 패턴)  (2) 2023.12.07
JAVA_추상클래스_#2_Pokemon  (2) 2023.12.06
JAVA_리턴타입 boolean인 메소드 연습_#1  (2) 2023.12.05
JAVA_상속_#3_Person  (0) 2023.12.03
JAVA_상속_#2_포켓몬  (1) 2023.12.03