Java - non-static variable this cannot be referenced from a static context 오류

김지현·2023년 3월 10일
0

오류모음집

목록 보기
3/4

오류내용

class cp6_19 {
	public static void main(String[] args) {
		MyMath mm = new MyMath();
		long result1 = mm.add(5L, 3L);
		long result2 = mm.subtract(5L, 3L);
		long result3 = mm.multiply(5L, 3L);
		double result4 = mm.divide(5L, 3L);

		System.out.println("add(5L, 3L) = " + result1);
		System.out.println("subtract(5L, 3L) = " + result2);
		System.out.println("multiply(5L, 3L) = " + result3);
		System.out.println("divide(5L, 3L) = " + result4);
	}

	class MyMath {
		long add(long a, long b) {
			long result = a + b;
			return result;
		}

		long subtract(long a, long b) {
			return a - b;
		}

		long multiply(long a, long b) {
			return a * b;
		}

		double divide(double a, double b) {
			return a / b;
		}
	}
}

MyMath mm = new MyMath();
참조변수 mm에 MyMath 객체의 주소를 저장하는 과정에서 오류가 남

해결방법

static 변수는 class가 로딩 된 이후에 실행될 수 있는 변수들임
따라서 class MyMath가 먼저 실행되어야 함
사실 맞는 지는 모르겠지만 class cp6_19 {} 안에 있던 class MyMath를 밖으로 빼서 따로 두니 오류가 해결됨

class cp6_19 {
	public static void main(String[] args) {
		MyMath mm = new MyMath();
		long result1 = mm.add(5L, 3L);
		long result2 = mm.subtract(5L, 3L);
		long result3 = mm.multiply(5L, 3L);
		double result4 = mm.divide(5L, 3L);

		System.out.println("add(5L, 3L) = " + result1);
		System.out.println("subtract(5L, 3L) = " + result2);
		System.out.println("multiply(5L, 3L) = " + result3);
		System.out.println("divide(5L, 3L) = " + result4);
	}
}

class MyMath {
	long add(long a, long b) {
		long result = a + b;
		return result;
	}

	long subtract(long a, long b) {
		return a - b;
	}

	long multiply(long a, long b) {
		return a * b;
	}

	double divide(double a, double b) {
		return a / b;
	}
}

0개의 댓글

관련 채용 정보