2023년 1월 1일
08:00 AM
Buffering ...

최근 글 👑

[명품자바 5장] 상속 실습문제

2023. 1. 10. 14:18ㆍ명품 자바 문제

 

[이것은 제가 직접 문제를 푼 것 임으로 다른 사이트와 내용적으로 다를 수 있습니다.]

 

 

[5장 1~2번]

 

다음 TV 클래스가 있다.

class TV{
   private int size;
   public TV(int size) { this.size = size; }
   protected int getSize() { return size; }
}

 

[1번] 다음 main() 메소드와 실행 결과를 참고하여 TV를 상속받은 ColorTV 클래스를 작성하라.

 

 

public static void main(String[] args) {
   ColorTV myTV = new ColorTV(32, 1024);
   myTV.printProperty();
}
32인치 1024컬러

 

[풀이]

 

 

 

 

 

 

class ColorTV extends TV {
   private int resolution;
   ColorTV(int size, int resolution) {
      super(size);
      this.resolution = resolution;
   }
   public void printProperty() {
      System.out.print(getSize()+"인치 "+resolution+"컬러");
   }
}

 

[2번] 다음 main() 메소드와 실행 결과를 참고하여 ColorTV를 상속받는 IPTV 클래스를 작성하라.

 

 

 

public static void main(String[] args) {
   IPTV iptv = new IPTV("192.1.1.2", 32, 2048); //"192.1.1.2" 주소에 32인치, 2048컬러
   iptv.printProperty();
}
나의 IPTV는 192.1.1.2 주소의 32인치 2048컬러

 

 

[풀이] (1번 풀이)

 

package 예제파일1번;

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.StringTokenizer;

public class ex15 {

    public static void main(String[] args) {
        ColorTV mytv = new ColorTV(32,1024);
        mytv.printProperty();
    }
}
class TV{
    private int size;
    private int color;
    public TV(int size,int color){
        this.size=size;
        this.color=color;
    }
    protected int getSize(){
        return size;
    }

    public int getColor() {
        return color;
    }
}
class ColorTV extends TV{

    public ColorTV(int size,int color) {
        super(size,color);
    }
    void printProperty(){
        System.out.println(getSize()+"인치"+" "+getColor()+"컬러");
    }
}

 

(2번 풀이)

 

package 예제파일1번;

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.StringTokenizer;

public class ex15 {

    public static void main(String[] args) {
        IPTV iptv = new IPTV("192.1.1.2",32,2048);
        iptv.printProperty();
    }
}
class TV{
    private int size;
    private int color;
    private String iptv;
    public TV(int size,int color,String iptv){
        this.size=size;
        this.color=color;
        this.iptv=iptv;
    }
    protected int getSize(){
        return size;
    }

    public int getColor() {
        return color;
    }
    public String getIptv(){
        return iptv;
    }
}
class ColorTV extends TV{


    public ColorTV(int size, int color, String iptv) {
        super(size, color, iptv);
    }
    void printProperty(){
        System.out.println(getSize()+"인치"+" "+getColor()+"컬러");
    }
}
class IPTV extends  ColorTV{


    public IPTV(String iptv,int size, int color) {
        super(size, color,iptv);
    }
    public void printProperty(){
        System.out.println("나의 iptv는 :"+getIptv()+"  주소의 "+getSize()+" 인치 "+getColor()+"컬러");
    }
}

 

실행 결과 :

 

 

 

[3번] Converter 클래스를 상속받아 원화를 달러로 변환하는 Won2Dollar 클래스를 작성하라. main() 메소드와 실행 결과는 다음과 같다.

 

 

 

 

 

 

 

public static void main(String args[]) {
   Won2Dollar toDollar = new Won2Dollar(1200); // 1달러는 1200원
   toDollar.run();
}
원을 달러로 바꿉니다.
원을 입력하세요>> 24000
변환 결과: 20.0달러입니다

 

package 예제파일1번;

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.StringTokenizer;

public class ex15 {
    public static void main(String[] args) {
        Won2Dollar won2Dollar = new Won2Dollar(24000);
        won2Dollar.run();

    }
}
abstract class Converter{
    abstract protected double convert(double src);
    abstract protected String getsrcString();
    abstract protected String getDestString();
    protected double ratio;

    public void run(){
        Scanner sc = new Scanner(System.in);
        System.out.println(getsrcString()+"을 "+getDestString()+"로 바꿉니다");
        System.out.println(getsrcString()+"을 입력하세요 >>");
        double val = sc.nextDouble();
        double res = convert(val);
        System.out.println("변환결과 :"+res+ getDestString()+"입니다");
        sc.close();
    }
}
class Won2Dollar extends Converter{

    Won2Dollar(int src){ //생성자를 이용해 24000을 src에 받아서 컨버트에 집어넣음
        this.convert(src);
    }

    @Override
    protected double convert(double src) {
        return src/1200; //1200원에 1달러니까 24000/1200을 하면 20달러가 나옴.
    }

    @Override
    protected String getsrcString() {
        return "원"; // 원을 리턴
    }

    @Override
    protected String getDestString() {
        return "달러"; // 달러를 리턴
    }
}

 

 

 

 

[4번] Converter 클래스를 상속받아 Km를 mile(마일)로 변환하는 Km2Mile 클래스를 작성하라, main() 메소드와 실행 결과는 다음과 같다.

 

 

 

 

 

 

public static void main(String args[]) {
   Km2Mile toMile = new Km2Mile(1.6); // 1마일은 1.6km
   toMile.run();
}
Km을 mile로 바꿉니다.
Km을 입력하세요>> 30
변환 결과: 18.75mile입니다

 

 

[풀이]

 

package 예제파일1번;

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.StringTokenizer;

public class ex15 {
    public static void main(String[] args) {
       Km2Mile tomile = new Km2Mile(1.6);
       tomile.run();

    }
}
abstract class Converter{
    abstract protected double convert(double src);
    abstract protected String getsrcString();
    abstract protected String getDestString();
    protected double ratio;

    public void run(){
        Scanner sc = new Scanner(System.in);
        System.out.println(getsrcString()+"을 "+getDestString()+"로 바꿉니다");
        System.out.println(getsrcString()+"을 입력하세요 >>");
        double val = sc.nextDouble();
        double res = convert(val);
        System.out.println("변환결과 :"+res+ getDestString()+"입니다");
        sc.close();
    }
}

class Km2Mile extends Converter{

    Km2Mile(double src){
        this.convert(src);
    }

    @Override
    protected double convert(double src) {
        return src/1.6;
    }

    @Override
    protected String getsrcString() {
        return "Km";
    }

    @Override
    protected String getDestString() {
        return "mile";
    }
}

 

 

실행결과 :

 

 

 

 

[5번] Point를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

 

 

 

 

 

 

 

 

public static void main(String[] args) {
   ColorPoint cp = new ColorPoint(5, 5, "YELLOW");
   cp.setXY(10, 20);
   cp.setColor("RED");
   String str = cp.toString();
   System.out.println(str+"입니다. ");
}
RED색의 (10,20)의 점입니다. 

 

package 예제파일1번;

public class ex15 {
    public static void main(String[] args) {
        ColorPoint cp = new ColorPoint(5,5,"Yellow");
        cp.setXY(10,20);
        cp.setColor("RED");
        String str = cp.toString();
        System.out.println(str+"입니다");
    }
}
class Point{
    private int x,y;
    public Point(int x, int y, String color){
        this.x=x; this.y=y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
    protected void move(int x,int y){
        this.x=x; this.y=y;
    }
}
class ColorPoint extends Point{
    private String color;

    public ColorPoint(int x, int y,String color) {
        super(x, y,color);
    }

    public void setColor(String color) {
        this.color = color;
    }
    public void setXY(int x,int y){
        move(x,y);
    }
    public String toString(){
        return color+" 색의 "+"("+getX()+","+getY()+")"+"의 점";
    }
}

 

 

[7번] Point를 상속받아 3차원의 점을 나타내는 Point3D 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

 

 

 

 

 

 

 

public static void main(String[] args) {
   Point3D p = new Point3D(1,2,3); // 1,2,3은 각각 x, y, z축의 값.
   System.out.println(p.toString()+"입니다.");
   p.moveUp(); // z 축으로 위쪽 이동
   System.out.println(p.toString()+"입니다.");
   p.moveDown(); // z 축으로 아래쪽 이동
   p.move(10, 10); // x, y 축으로 이동
   System.out.println(p.toString()+"입니다.");
   p.move(100,  200, 300); // x, y, z축으로 이동
   System.out.println(p.toString()+"입니다.");
}
(1,2,3) 의 점입니다.
(1,2,4) 의 점입니다.
(10,10,3) 의 점입니다.
(100,200,300) 의 점입니다.

 

package 예제파일1번;

public class ex15 {
    public static void main(String[] args) {
      Point3D p = new Point3D(1,2,3);
      System.out.println(p.toString()+"입니다");

      p.moveup();
      System.out.println(p.toString()+"입니다");

      p.moveDown();
      p.move(10,10);
      System.out.println(p.toString()+"입니다");

      p.move(100,200,300);
      System.out.println(p.toString()+"입니다"); //오버로딩 해야 함.
    }
}
class Point{
    private int x,y,z;
    private String color;
    public Point(int x, int y, int z){ //첫번째 답 1,2,3을 받는 생성자.
        this.x=x; this.y=y; this.z=z;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
    protected void move(int x,int y){
        this.x=x; this.y=y;
    }
    protected void move(int x,int y,int z){ //오버로딩된 메서드.
        this.x=x; this.y=y; this.z=z;
    }

    public String getColor() {
        return color;
    }
    public int  getZ(){
        return z;
    }
    protected int moveup(){ //moveup 메서드를 만들어 getz+1을 해서 result에 넣어줌.
        int result = setZ(getZ()+1);
        return  result;
    }

    public int setZ(int z) { // get+1의 값을 받기 위해서는 set메서드를 만들어 값을 넘겨줘야 한다.
        this.z=z;
        return this.z;
    }
    protected int moveDown(){
        int result = setZ(getZ()-1);
        return result;
    }
}
class Point3D extends Point{


    public Point3D(int x, int y,int z) {
        super(x, y, z);
    }
    public String toString(){
        String Z = "("+getX()+","+getY()+","+getZ()+")";
        return Z;
    }
}

 

 

 

 

[8번] Point를 상속받아 양수의 공간에서만 점을 나타내는 PositivePoint 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

 

 

 

 

 

 

 

public static void main(String[] args) {
   PositivePoint p = new PositivePoitn();
   p.move(10, 10);
   System.out.println(p.toString()+"입니다.");
   p.move(-5,5); // 객체 p는 음수 공간으로 이동되지 않음
   System.out.println(p.toStrgin()+"입니다.");
   PositivePoint p2 = new PositivePoint(-10, -10);
   System.out.println(p2.toString()+"입니다.");
}
(10,10)의 점입니다.
(10,10)의 점입니다.
(0,0)의 점입니다.

 

 

 

[Hint] Point 클래스의 move()를 PositivePoint 클래스에서 오버라이딩하여 재작성하고 적절히 super.move()를 호출해야 한다. PositivePoint의 2 개의 생성자에서도 적절히 super() 생성자와 super.move()를 호출해야 한다.

 

 

 

 

 

package 예제파일1번;

public class ex15 {
    public static void main(String[] args) {
     PositivePoint p  = new PositivePoint();
     p.move(10,10);
     System.out.println(p+"입니다"); //toString을 쓰나 p를 쓰나 값은 같다.
        //이유: 객체 메서드에 toString을 만들었기 때문에 굳이 안써도 된다.

        p.move(-5,5);
        System.out.println(p+"입니다");

        PositivePoint p2 = new PositivePoint(-10,-10);
        System.out.println(p2+"입니다");
    }
}
class Point{

    Point(){}


    Point(int x,int y){

        if(x<0 || y<0){
            x=0; y=0;
            this.x=x;
            this.y=y;
        }
        else this.x=x; this.y=y;
    }

    private int x,y,z;
    private String color;

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
    protected int  move(int x, int y){


        if(x<0 || y<0){
            return 0;
        }else this.x=x; this.y=y;
        return 0;
    }
    protected void move(int x,int y,int z){
        this.x=x; this.y=y; this.z=z;
    }

    

}
class PositivePoint extends Point{
        private int x=0;
        private int y=0;
    PositivePoint(int x,int y){
        super(x,y);
    }
    PositivePoint(){
    }

    public String toString(){
        return "("+getX()+","+getY()+")";
    }
}

 

 

 

[5장 9번]

 

다음 Stack 인터페이스를 상속받아 실수를 저장하는 StringStack 클래스를 구현하라.

 

 

interface Stack {
   int length(); // 현재 스택에 저장된 개수 리턴
   int capacity(); // 스택의 전체 저장 가능한 개수 리턴
   String pop(); // 스택의 톱(top)에 실수 저장
   boolean push(String val); // 스택의 톱(top)에 저장된 실수 리턴
}

그리고 다음 실행 사례와 같이 작동하도록 StackApp 클래스에 main() 메소드를 작성하라.

 

 

 

총 스택 저장 공간의 크기 입력 >> 3
문자열 입력 >> hello
문자열 입력 >> sunny
문자열 입력 >> smile
문자열 입력 >> happy
스택이 꽉 차서 푸시 불가!
문자열 입력 >> 그만
스택에 저장된 모든 문자열 팝 : smile sunny hello 

 

 

 

 

 

 

 

package 예제파일1번;

import java.util.Scanner;

interface Stack {
    int length(); // 현재 스택에 저장된 개수 리턴
    int capacity(); // 스택의 전체 저장 가능한 개수 리턴
    String pop(); // 스택의 톱(top)에 실수 저장
    boolean push(String val); // 스택의 톱(top)에 저장된 실수 리턴
}

class StringStack implements Stack {
    private int num; // 저장 가능한 개수
    private int set; // 저장 인덱스
    private String[] stack;
    public StringStack(int num) {
        this.num = num;
        this.set = 0;
        stack = new String[num];
    }
    public int length() {
        return set;
    }
    public int capacity() {
        return stack.length;
    }
    public String pop() {
        if(set-1 < 0)  // stack에 아무것도 넣지 않았을 떄
            return null;
        set--; // stack 한칸을 내려줌 (stack[set]은 빈공간을 가리키고 있으니깐)
        String s = stack[set]; // 맨 위의 값
        return s;
    }
    public boolean push(String val) {
        if(set < num) {
            stack[set] = val; //맨 위에 문자열을 넣어줌
            set++; // stack 한칸을 올려줌
            return true;
        }
        else
            return false;
    }
}

public class StackApp implements Stack {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.print("총 스택 저장 공간의 크기 입력 >> ");
        int num = sc.nextInt();
        StringStack stack = new StringStack(num);
        while(true) {
            System.out.print("문자열 입력 >> ");
            String val = sc.next();
            if(val.equals("그만"))
                break;
            if(!stack.push(val)) {
                System.out.println("스택이 꽉 차서 푸시 불가!");
            }
        }
        System.out.print("스택에 저장된 모든 문자열 팝 : ");
        int len = stack.length();
        for(int i=0; i<len; i++) {
            String s = stack.pop();
            System.out.print(s+" ");
        }
        sc.close();
    }

    @Override
    public int length() {
        return 0;
    }

    @Override
    public int capacity() {
        return 0;
    }

    @Override
    public String pop() {
        return null;
    }

    @Override
    public boolean push(String val) {
        return false;
    }
}

 

 

 

 

 

 

 

[5장 10번]

 

다음은 키와 값을 하나의 아이템으로 저장하고 검색 수정이 가능한 추상 클래스가 있다.

 

 

 

 

 

abstract class PairMap {
   protected String KeyArray[]; // key 들을 저장하는 배열
   protected String valueArray[]; // value 들을 저장하는 배열
   abstract String get(String key); // key 값을 가진 value 리턴, 없으면 null 리턴
   abstract void put(String ket, String value); // key와 value를 쌍으로 저장. 기존에 key가 있으면, 값을 value로 수정
   abstract String delete(String key); // key 값을 가진 아이템 (value와 함꼐) 삭제, 삭제된 value 값 리턴
   abstract int length(); // 현재 저장된 아이템의 개수 리턴
}

 

 

 

PairMap을 상속받는 Dictionary 클래스를 구현하고, 이를 다음과 같이 활용하는 main() 메소드를 가진 클래스 DictionaryApp도 작성하라.

 

 

 

 

 

public static void main(String[] args) {
   Dictionary<K, V> dic = new Dictionary(10);
   dic.put("황기태", "자바");
   dic.put("이재문", "파이선");
   dic.put("이재문", "C++"); // 이재문의 값을 C++로 수정
   System.out.println("이재문의 값은 "+dic.get("이재문"));
   System.out.println("황기태의 값은 "+dic.get("황기태"));
   dic.delete("황기태"); // 황기태 아이템 삭제
   System.out.println("황기태의 값은 "+dic.get("황기태")); //삭제된 아이템 접근
이재문의 값은 C++
황기태의 값은 자바
황기태의 값은 null

 

package 예제파일1번;

import java.util.Scanner;

abstract class PairMAP{
    protected String keyArray[];
    protected String valueArray[];
    abstract String get(String key);
    abstract void put(String key,String value);
    abstract String delete(String key);
    abstract int length();
}

public class chap06_prac08 {
    public static void main(String[] args) {
        Dictionary dic = new Dictionary(10);
        dic.put("황기태","자바");
        dic.put("이재문","파이썬");
        dic.put("이재문","C++");
        System.out.println("이재문의 값은 :"+dic.get("이재문"));
        System.out.println("황기태의 값은 :"+dic.get("황기태"));
        dic.delete("황기태");
        System.out.println("황기태의 값은 :"+dic.get("황기태"));

    }
}
class Dictionary extends PairMAP{
    String[] array;
    int number =0;
    Dictionary(int number){
     keyArray = new String[number];
     valueArray = new String[number];
    }

    @Override
    String get(String key) {
        for(int i=0;i< keyArray.length;i++){
            if(keyArray[i].equals(key)){
                return valueArray[i];
            }
        }
        return null;
    }

    @Override
    void put(String key, String value) {
      for(int i=0;i< keyArray.length;i++) {
          if(keyArray[i]==null&&valueArray[i]==null) {
              keyArray[i] = key;
              valueArray[i] = value;
          }
              if(keyArray[i].equals(key)){
                  keyArray[i] = key; valueArray[i] = value;
                  break;
              }

      }
    }

    @Override
    String delete(String key) {
        for(int i=0; i< keyArray.length;i++){
            if(keyArray[i].equals(key)){
                valueArray[i]=null;
            }
            return valueArray[i];
        }
        return null;
    }

    @Override
    int length() {
        return 0;
    }
}

 

 

 

 

 

 

 

 

 

 

사실은 이런문제는 자료구조를 사용할 수 있다면 훨씬 쉽게 풀 수 있습니다.

바로 자료구조의 map을 사용하면 됩니다.

 

자료구조를 사용해서 문제를 보고 싶다면 더보기를 눌러주세요

 

더보기
package 예제파일1번;

import java.security.Key;
import java.util.HashMap;
import java.util.Scanner;

abstract class PariMap{

    protected String keyArray[]; //key 들을 저장하는 배열
    protected String valueArray[]; // value 들을 저장하는 배열
    abstract String get(String key); // key 값을 가진 value 리턴 . 없으면 null 리턴
    abstract void put(String key,String value); // key와 value를 쌍으로 저장. 기존에 key가 있으면
    //값을 value로 수정
    abstract String delete(String key);
    abstract int length();

}
public class DictionaryAPP{
    public static void main(String[] args) {

        HashMap hashMap = new HashMap();
        hashMap.put("황기태","자바");
        hashMap.put("이재문","파이썬");
        hashMap.put("이재문","C++");


        System.out.println("이재문의 값은 : "+hashMap.get("황기태"));
        System.out.println("황기태의 값은 : "+hashMap.get("이재문"));

        hashMap.remove("황기태");
        System.out.println("황기태의 값은 :"+hashMap.get("황기태"));




    }
}
class Dictionary extends PariMap {

    @Override
    String get(String key) {
        return null;
    }

    @Override
    void put(String key, String value) {

    }

    @Override
    String delete(String key) {
        return null;
    }

    @Override
    int length() {
        return 0;
    }
}

보는대로 상속받은 것을 아무것도 건드리지않고 hashmap으로만 값들을 저장해서 적용시켰습니다.

나중에 자료구조를 배우겠지만 자료구조를 사용하면 이런 난해한 문제 같은경우들도 아주 쉽게 사용 할 수 있습니다.

 

 

 

 

 

 

 

[5장 11번]

 

철수 학생은 다음 3개의 필드와 메소드를 가진 4개의 클래스 Add, Sub, Mul, Div를 작성하려고 한다(4장 실습문제 11 참고).

- int 타입의 a, b 필드: 2개의 피연산자
- void setValue(int a, int b): 피연산자 값을 객체 내에 저장한다.
- int calculate(): 클래스의 목적에 맞는 연산을 실행하고 결과를 리턴한다.

 

 

곰곰 생각해보니, Add, Sub, Mul, Div 클래스에 공통된 필드와 메소드가 존재하므로 새로운 추상 클래스 Calc를 작성하고 Calc를 상속받아 만들면 되겠다고 생각했다. 그리고 main() 메소드에서 다음 실행 사례와 같이 2개의 정수와 연산자를 입력받은 후, Add, Sub, Mul, Div 중에서 이 연산을 처리할 수 있는 객체를 생성하고 setValue() 와 calculate()를 호출하여 그 결과 값을 화면에 출력하면 된다고 생각하였다. 철수처럼 프로그램을 작성하라.

 

 

 

 

두 정수와 연산자를 입력하시오 >> 5 7 +
12

 

 

 

package 예제파일1번;

import javax.swing.plaf.synth.SynthIcon;
import java.security.Key;
import java.util.HashMap;
import java.util.Scanner;


abstract class Calc {
    int a=0;
    int b=0;



    void setValue(int a, int b){
        this.a=a; this.b=b;

    }

    int calculate(){

        return 0;
    }
}

class Add extends Calc{


    @Override
    public void setValue(int a, int b) {
        super.a=a; super.b=b;
    }

    @Override
    public int calculate() {
        return super.a+super.b;
    }
}
class Sub extends Calc{
    @Override
    void setValue(int a, int b) {
        super.setValue(a, b);
    }

    @Override
    int calculate() {
        return super.a-super.b;
    }
}
class Mul extends Calc{
    @Override
    void setValue(int a, int b) {
        super.setValue(a, b);
    }

    @Override
    int calculate() {
        return super.a*super.b;
    }

}

class Div extends Calc{
    @Override
    int calculate() {
        return super.a/super.b;
    }

    @Override
    void setValue(int a, int b) {
        super.setValue(a, b);
    }
}
public class Cal{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Add add = new Add();
        Sub sub = new Sub();
        Mul mul = new Mul();
        Div div = new Div();

        System.out.println("두 정수와 연산자를 입력하세요 .");
        int a =sc.nextInt();
        int b= sc.nextInt();
        String cal = sc.next();
        switch (cal){
            case "+":
              add.setValue(a,b);
              System.out.println(add.calculate());
              break;
            case "-":
                sub.setValue(a,b);
                System.out.println(sub.calculate());
                break;
            case "*":
                mul.setValue(a,b);
                System.out.println(mul.calculate());
                break;
            case "/":
                div.setValue(a,b);
                System.out.println(div.calculate());
                break;



        }
    }
}

 

 

 

 

다음은 도형의 구성을 묘사하는 인터페이스이다.

 

 

 

interface Shape {
   final double PI = 3.14; // 상수
   void draw(); // 도형을 그리는 추상 메소드
   double getArea(); // 도형의 면적을 리턴하는 추상 메소드
   default public void redraw() { // 디폴트 메소드
      System.out.print("--- 다시 그립니다.");
      draw();
   }
}

 

 

 

 

 

다음 main() 메소드와 실행 결과를 참고하여, 인터페이스 Shape을 구현한 클래스 Circle를 작성하고 전체 프로그램을 완성하라.

 

 

 

public static void main(String[] args) {
   Shape donut = new Circle(10); // 반지름이 10인 원 객체
   donut.redraw();
   System.out.println("면적은 "+ donut.getArea());
}

 

 

[풀이]

class Circle implements Shape {
   private int radius;
   public Circle(int radius) {
      this.radius = radius;
   }
   public void draw() {
      System.out.println("반지름이 "+radius+"인 원입니다.");
   }
   public double getArea() {
      return PI*radius*radius;
   }
}

 

 

 

 

[5장 14번]

 

다음 main() 메소드와 실행 결과를 참고하여, 문제 13의 Shape 인터페이스를 구현한 클래스 Oval, Rect를 추가 작성하고 전체 프로그램을 완성하라.

 

 

 

public static void main(String[] args) {
   Shape[] list = new Shape[3]; // Shape을 상속받은 클래스 객체의 레퍼런스 배열
   list[0] = new Circle(10); // 반지름이 10인 원 객체
   list[1] = new Oval(20, 30); // 20x30 사각형에 내접하는 타원
   list[2] = new Rect(10, 40); // 10x40 크기의 사각형
   for(int i=0; i<list.length; i++) list[i].redraw();
   for(int i=0; i<list.length; i++) System.out.println("면적은 "+ list[i].getArea());
}
--- 다시 그립니다.반지름이 10인 원입니다.
--- 다시 그립니다.20x30에 내접하는 타원입니다.
--- 다시 그립니다.10x40크기의 사각형 입니다.
면적은 314.0
면적은 1884.0000000000002
면적은 400.0

 

 

 

package 예제파일1번;

public class ex13 {
    public static void main(String[] args) {
        Shape donut = new Circle(10);
        donut.redraw();
        System.out.print("면적은 :"+donut.getArea());
    }
}
interface Shape {
    final double PI = 3.14;
    void draw();
    double getArea();
    default public void redraw(){
        System.out.print("---다시 그립니다");
        draw();
    }
}
class Circle implements Shape{

    int number =0;

    Circle(int number){
        this.number=number;
    }

    @Override
    public void draw() {

    }

    @Override
    public double getArea() {
        return PI*(number*number);
    }

    @Override
    public void redraw() {
        System.out.println("다시 그립니다. 반지름이 :"+number+"인 원 입니다.");
    }
}

 

 

 

 

[5장 14번]

 

다음 main() 메소드와 실행 결과를 참고하여, 문제 13의 Shape 인터페이스를 구현한 클래스 Oval, Rect를 추가 작성하고 전체 프로그램을 완성하라.

 

 

 

public static void main(String[] args) {
   Shape[] list = new Shape[3]; // Shape을 상속받은 클래스 객체의 레퍼런스 배열
   list[0] = new Circle(10); // 반지름이 10인 원 객체
   list[1] = new Oval(20, 30); // 20x30 사각형에 내접하는 타원
   list[2] = new Rect(10, 40); // 10x40 크기의 사각형
   for(int i=0; i<list.length; i++) list[i].redraw();
   for(int i=0; i<list.length; i++) System.out.println("면적은 "+ list[i].getArea());
}
--- 다시 그립니다.반지름이 10인 원입니다.
--- 다시 그립니다.20x30에 내접하는 타원입니다.
--- 다시 그립니다.10x40크기의 사각형 입니다.
면적은 314.0
면적은 1884.0000000000002
면적은 400.0

 

 

 

package 예제파일1번;

public class ex13 {
    public static void main(String[] args) {
       Shape[] list = new Shape[3]; //인터페이스에 의해서 모든 타입이 Shape로 정해짐.
       list[0] = new Circle(10); // 다형성에 의해서 Circle의 타입은 Shape임.
       list[1] = new Oval(20,30);// ""
       list[2] = new Rect(10,40);//""
       for(int i=0;i<list.length;i++){
           list[i].redraw();
       }
       for(int j=0;j<list.length;j++){
           System.out.println("면적은 :"+list[j].getArea());
       }
    }
}
interface Shape {

    final double PI = 3.14;
    void draw();
    double getArea();
    default public void redraw(){
        System.out.print("---다시 그립니다");
        draw();
    }
}

class Oval implements Shape{
    int number = 0;
    int number1 = 0;
    Oval(int number,int number1){ // 인터페이스는 생성자를 가질 수 없음으로 자식메서드에 생성자 생성
        this.number=number; this.number1=number1;
    }

    @Override
    public void draw() {

    }

    @Override
    public double getArea() {
        return PI*(number*number1);
    }

    @Override
    public void redraw() { //인터페이스에서는 생성자로 받은 number과 number1이 없기 떄문에 자식 메서드에서 정의 해줘야 함.
        System.out.println("---다시 그립니다."+number+"x"+number1+" 크기의 사각형 입니다.");
    }
}
class Circle implements Shape{
    int number =0;
    Circle(int number){
        this.number=number;
    }


    @Override
    public void draw() {

    }

    @Override
    public double getArea() {
        return PI*(number*number);
    }

    @Override
    public void redraw() {
       System.out.println("---다시 그립니다. 반지름이 :"+number+"인 원입니다.");
    }
}

class Rect implements Shape{
    int number = 0;
    int number1 =0;
    Rect(int number,int number1){
        this.number=number; this.number1=number1;

    }

    @Override
    public void draw() {

    }

    @Override
    public double getArea() {
        return number*number1;
    }

    @Override
    public void redraw() {
        System.out.println("---다시 그립니다. "+number+"x"+number1+"에 내접하는 타원입니다.");
    }
}

 

[결과화면]