오류노트

[코딩 오류 노트] 클래스 메서드에서 인스턴스 메서드, 메서드 중복/파라미터값

망고고래 2023. 10. 19. 17:46

1. 클래스 메서드에서 인스턴스 메서드에 접근

오류 메시지

Cannot make a static reference to the non-static field iv

Cannot make a static reference to the non-static method im() from the type Check

 

코드

//(별개의 클래스)
int iv = 4; void im()
{

}

//(메인 클래스 메인 함수 안)
static void cm_Imember()
{
System.out.println(iv);
im();
}

 

해결

클래스 멤버는 인스턴스 멤버를 참조하거나 호출할 수 없다.

 

 

 

2. 메서드 중복

오류 메시지

Duplicate method sum(int a, int b, int c) in type exam6_38(클래스명)

*프로그램 실행은 됨

 

코드

static int sum(int a, int b, int c)
{
System.out.println("인자가 셋일 경우 호출됨");
return a+b+c;
}
static int sum(int a, int b, int c)
{
System.out.println("인자가 셋일 경우 호출됨");
return a+b+c;
}

 

해결

오버로딩을 이용하면 이름이 같은 함수를 여러 개 생성할 수 있지만, 인자의 타입이나 수가 달라야 한다.

 

 

 

3. 메서드에 지정된 인자 개수와 파라미터 개수 불일치

오류 메시지

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

The method sum(int, int, int) in the type exam6_38 is not applicable for the arguments (int, int)

 

코드

int sum(int a, int b, int c)
{
System.out.println("인자가 셋일 경우 호출됨");
return a+b+c;
}
System.out.println(sum(2, 3));

 

해결

인자 개수와 파라미터 개수를 일치시킨다.

또는 오버로딩을 이용해 다양한 파라미터 타입에 유연하게 대처할 수 있다.

 

 

4. 파라미터값과 리턴값의 타입 불일치

오류 메시지

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

Type mismatch: cannot convert from double to int

 

코드

static int sum(double a, double b, double c)
{
return a+b+c;
}

 

해결

static int sum(double a, double b, double c)

{

      return (int)(a+b+c);

}

파라미터값과 리턴값의 타입은 일치시킨다.

 

 

 

5. 매개변수가 있는 생성자를 호출할 때 파라미터값을 주지 않음

오류 메시지

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

The constructor Cellphone() is undefined

 

코드

class Cellphone
{
     String model = "Galaxy 8";
     String color; int capacity;
     Cellphone(String color, int capacity)
        {
             this.color = color; this.capacity = capacity;
        }
}

public class Constructor1 {
    public static void main(String[] args)
    {
Cellphone myphone1 = new Cellphone();
     }
}

 

해결

파라미터값이 필요한 생성자에는 값을 주도록 한다.