오류노트

[코딩 오류 노트] 클래스, 인스턴스, 메서드

망고고래 2023. 10. 17. 17:44

1. 클래스 이름 중복

오류 메시지

The type Class_practice is already defined

 

코드

public class Class_practice
{
   public static void main(String[] args)
   {
Car mycar = new Car();
   } 
}
class Class_practice
{
}

 

해결

클래스 이름은 중복되지 않도록 한다.

 

 

 

2. 클래스 파일 이름과 퍼블릭 클래스 이름 불일치

오류 메시지

The public type Class must be defined in its own file

 

코드

public class Class
{

}

(파일명: Class_practice)

 

해결

클래스 파일 이름과 퍼블릭 클래스를 일치시킨다.

 

 

 

3. 다른 클래스에서 만든 인스턴스 변수에 접근

오류 메시지

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

Cannot make a static reference to the non-static field cars.speed

 

코드


class cars
{
    static int wheel = 4;
    int speed;
}

public class class_practice3
{
    public static void main(String[] args)
   {
        System.out.println(cars.wheel);
        System.out.println(cars.speed);
    }
}

 

해결

다른 클래스에서 만들어진 인스턴스 변수에 접근하려면 new를 사용해 인스턴스를 생성해야 한다.

 

 

 

4. 메서드에 return값 미입력

오류 메시지

This method must return a result of type int

 

코드

int plus()
{

}

 

해결

int plus(int a, int b)

{

return a+b;

}

리턴 타입이 void가 아닌 경우 반드시 return값을 입력한다.

 

 

 

5. 메서드에 변수명 미입력

오류 메시지

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

The method plus() in the type sub is not applicable for the arguments (int, int)

 

코드

int plus()
{

}

if(calcul.equals("+"))
{
sb.plus(first, second);
}

 

해결

int plus(int a, int b)

{

return a+b;

}

 

 

 

6. 클래스에 변수와 함수 외 입력

오류 메시지

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

 

코드

class sub
{
System.out.println("0");

 

해결

클래스 안에는 변수와 함수만 사용할 수 있다.

 

 

 

7. 인스턴스에 접근할 때 클래스명.메서드명(); 사용

오류 메시지

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

Cannot make a static reference to the non-static method 제품생산() from the type 생산직원

 

코드

생산직원 직원1 = new 생산직원();
String 제품 = 생산직원.제품생산();

 

 

해결

변수에 접근할 경우: 참조변수.변수명

메서드를 실행시킬 경우: 참조변수.메서드명();