JAVA_

JAVA#16 _ 객체 지향 언어 문제 연습

Joyfullyever 2025. 1. 12. 01:27

Q1. 

원 클래스를 선언해주세요. 원 객체는 이름, 반지름, 넓이를 가집니다.

class Circle {

String name;

int radius;

double area; // 멤버 변수 선언

 

Circle(String name, int radius) {

this.name = name;

this.radius = radius;

this.area = this.radius * this.radius * 3.14; // 멤버 변수 초기화

}

 

void printCircleArea() {

System.out.println("원 이름 : " + this.name);

System.out.println("반지름 : " + this.radius);

}

}

 

Q2.

책 객체들을 저장하고 싶습니다. 책 객체는 제목과 작가를 가집니다. 작가를 알 수 없는 경우, "작자미상"으로 표기합니다.

class Book {

String title;

String writter; // 멤버 변수 선언

 

Book(String title) {

this.title = title;

this.writter = "작자미상"; // 멤버 변수 초기화

}

 

Book(String title, String writter) {

this.title = title;

this.writter = writter;

}

 

void printBookInfo() {

System.out.println("책 이름 : " + this.title);

System.out.println("작가 이름 : " + this.writter);

}

}

 

Q3.

상품 객체를 다룰 예정입니다. 상품 객체는 이름, 가격, 재고를 가집니다. 재고를 설정하지 않은 경우 "0"으로 표기합니다.

class Product {

String name;

int price;

int num // 멤버 변수 선언

 

Product(String name, int price) {

this.name = name;

this.price = price;

this.num = 0; // 멤버 변수 초기화

}

 

Product(String name, int price, int num) {

this.name = name;

this.price = price;

this.num = num;

}

 

void printProductInfo() {

System.out.println("제품 이름 : " + this.name);

System.out.println("제품 가격 : " + this.price + "원");

System.out.println("제품 재고 : " + this.num + "개");

}

}

 

Q4.

자동차 클래스를 구현해주세요. 자동차는 현재 속도를 보여줄 수 있고, 모든 자동차들은 최대 속도가 120을 넘길 수 없습니다.

class Car {

int carCurrentSpeed;

int carMaxSpeed;  // 멤버 변수 선언

 

Car(int carCurrentSpeed) {

this.carCurrentSpeed = carCurrentSpeed;

this.carMaxSpeed = 120; // 멤버 변수 초기화

 

if (this.carCurrentSpeed > this.carMaxSpeed) {

this.carCurrentSpeed = this.carMaxSpeed;

System.out.println("자동차의 최고 속도는 " + this.carMaxSpeed + " km/h 입니다.");

}

}

}

 

Q1~4 출력

Circle circle01 = new Circle("피자", 3);

circle01.printCircleArea();

 

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

 

Book book01 = new Book("해리 포터", "JK 롤링");

book01.printBookInfo();

 

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

 

Product prod01 = new Product("핸드폰", 1000000, 333);

prod01.printProductInfo();

 

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

 

Car car01 = new Car(110);

System.out.println("자동차의 현재 속도 : " + car01.carCurrentSpeed);

 

Console 창 출력

원 이름 : 피자

반지름 : 3

================================

책 이름 : 해리 포터

작가 이름 : JK 롤링

================================

제품 이름 : 핸드폰

제품 가격 : 1000000원

제품 재고 : 333개

================================

자동차의 현재 속도 : 110