데이터 과학

생성자 선언 관련 문제 본문

AP/AP Computer Science A

생성자 선언 관련 문제

티에스윤 2024. 1. 11. 23:12

생성자를 선언할 때 주의점이 있습니다. 

 

AP Com. A 시험에 간혹 나오는 문제입니다. 

아래 예제는 https://tsyoon.tistory.com/113 에 있는 예제에 매개변수 없는 기본 객체를 선언한 예제입니다. 

 

 

 

class Box {
   private int width; 
   private int height;
   private int depth; 
   private int vol;  

    public Box(int a, int b, int c) { // 클래스의 이름과 같은 이름으로 생성자 선언 
         width = a; 
         height = b; 
         depth = c; 
}

    public int volume() { 
         vol = width * height * depth; 
         return vol; 
     } 
}


public class BoxTestDemo { 
     public static void main(String args[]) { 
         int vol;  
         Box mybox1 = new Box(10, 20, 30); 
         Box mybox2 = new Box(); // 기본 형태의 객체를 선언합니다.  
         vol = mybox1.volume(); 
System.out.println("mybox1 객체의 부피 : " + vol); 
   } 
}

 

기본 객체를 선언하는 경우는 생성자를 선언하지 않아도 되었습니다. 하지만, 위의 예제에는 이미 매개변수가 3개가 있는 

 

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

 

생성자가 선언되어 있습니다. 이럴때는 기본 객체도 생성자를 만들어서 선언을 해야 합니다. 

그렇지 않으면 아래와 같은 에러가 나옵니다. 

 

 

BoxTestDemo.java:25: error: constructor Box in class Box cannot be applied to given types;
         Box mybox2 = new Box(); // 기본 형태의 객체를 선언합니다.  
                      ^
  required: int,int,int
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error

 

 

다시 프로그램을 작성합니다. 

 

 

class Box {

   private int width; 
   private int height;
   private int depth; 
   private int vol;  


   public Box() {    // 추가로 만들어줘야 합니다. 
         width = 0; 
         height = 0; 
         depth = 0; 
}

    public Box(int a, int b, int c) { // 클래스의 이름과 같은 이름으로 생성자 선언 
         width = a; 
         height = b; 
         depth = c; 
}

    public int volume() { 
         vol = width * height * depth; 
         return vol; 
     } 
}


public class BoxTestDemo { 
     public static void main(String args[]) { 
         int vol;  
         Box mybox1 = new Box(10, 20, 30); 
         Box mybox2 = new Box(); // 기본 형태의 객체를 선언합니다.  
         vol = mybox1.volume(); 
System.out.println("mybox1 객체의 부피 : " + vol); 
   } 
}

 

기본 생성자를 하나 만들어 주어야 문제없이 컴파일됩니다. 

 

 

'AP > AP Computer Science A' 카테고리의 다른 글

static 변수  (0) 2024.05.29
ArrayList 예제  (0) 2024.01.12
Blue J 설치  (0) 2024.01.07
super 예제  (1) 2024.01.05
상속 예제  (0) 2024.01.04