ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 상자의 정보 (함수 재정의)
    코딩/java 2019. 3. 8. 16:32
    반응형

    public class Box {

    private int x;

    private int y;

    private int z;

    private boolean empty;

     

    public String toString() {

    String rslt = "가로: " + x + "cm 세로: " + y + "cm 높이: " + z + "cm";

    return rslt;

      }

     

    public void fillBox() {

    this.empty = false;

      }

     

    public void emptyBox() {

    this.empty = true;

      }

     

    public int getVolume() {

    return x * y * z;

      }

     

    public double getWeight() {

    return 1.1 * getVolume();

      }

     

    public Box(int x, int y, int z) {

    this.x = x;

    this.y = y;

    this.z = z;

    emptyBox();

      }

    }

     

     

    public class MaterialBox extends Box{

    private String attribute;

     

    public void setAttribute(String attribute) {this.attribute = attribute;};

    public String getAttribute() {return attribute;};

     

    public double getWeight() {

    if (attribute.equals("paper")) {

    return getVolume() * 1.5;

    } else if (attribute.equals("wood")) {

    return getVolume() * 2.5;

    } else {

    return getVolume() * 1.1;

    }

      }

     

    public String toString() {

    return super.toString() + "\n재질: " + attribute;

      }

     

    public MaterialBox(int x, int y, int z, String attribute) {

    super(x, y, z);

    this.attribute = attribute;

      } 

    }

     

     

    public class Practice_74 {

     

    public static void main(String[] args) {

    Box box1 = new Box(10, 20, 30);

    MaterialBox box2 = new MaterialBox(2, 3, 4, "wood");

    MaterialBox box3 = new MaterialBox(4, 3, 2, "paper");

     

    System.out.println("box1의 정보입니다.");

    System.out.println(box1.toString() + "\n부피: " + box1.getVolume() + "\n무게: " + box1.getWeight());

     

    System.out.println("box2의 정보입니다.");

    System.out.println(box2.toString() + "\n부피: " + box2.getVolume() + "\n무게: " + box2.getWeight());

     

    System.out.println("box3의 정보입니다.");

    System.out.println(box3.toString() + "\n부피: " + box3.getVolume() + "\n무게: " + box3.getWeight());

    }

     

    }

     

     

    결과:

     

     

    반응형

    '코딩 > java' 카테고리의 다른 글

    사각형 넓이 비교  (0) 2019.03.18
    키, 몸무게 비교  (0) 2019.03.18
    학생 정보 (함수 재정의)  (0) 2019.03.08
    학생 정보 출력 (super)  (0) 2019.03.08
    상자 정보 (상속 super)  (0) 2019.03.04
Designed by Tistory.