JAVA/객체지향 프로그래밍 I

객체지향 프로그래밍 I(object-oriented programming I)_2

whale_it 2018. 8. 17. 10:58

3.변수와 메서드

3.1 선언위치에 따른 변수의 종류

class Variable{
    int iv; // 인스턴스 변수
    static int cv; // 클래스 변수(static 변수)
    
    void method(){
        int lv = 0; // 지역 변수
    }
}
변수의 종류선언위치생성시기
클래스변수(class)클래스 영역클래스가 메모리에 올라갈 때
인스턴스 변수(instance)클래스 영역인스턴스가 생성되었을 때
지역 변수(local)클래스 영역 이외(메서스, 생성자등)변수 선언문 선언 시

3.1.1 인스턴스 변수(instance variable)

  • 클래스의 인스턴스 생성시 생성됨
  • 독립적인 공간을 가지며 각 인스턴스 마다 서로 다른 값 유지

3.1.2 클래스 변수(class variable)

  • 인스턴스 변수 앞에 static 사용
  • 공통된 저장 공간을 가지므로 한 클래수의 공통적인 값을 유지 시 사용
  • 인스턴스화 필요 없이 클래스명.변수명 으로 바로 사용

3.1.3 지역 변수(local variable)

  • 메서드 내 선언 및 사용
  • 메서드 종료 시 소멸 됨

 

3.2 클래스변수와 인스턴스 변수

package ch06;
class CardTest{
	public static void main(String args[]) {
		System.out.println("Card.width = "  + Card.width);
		System.out.println("Card.height = " + Card.height);

		Card c1 = new Card();
		c1.kind = "Heart";
		c1.number = 7;

		Card c2 = new Card();
		c2.kind = "Spade";
		c2.number = 4;

		System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")" );
		System.out.println("c2는 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")" );		

		System.out.println("c1의 width와 height를 각각 50, 80으로 변경합니다.");
		c1.width = 50;
		c1.height = 80;

		System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")" );
		System.out.println("c2는 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")" );
	}
 }

class Card {
	String kind ;				// 카드의 무늬 - 인스턴스 변수
	int number;				    // 카드의 숫자 - 인스턴스 변수
	static int width = 100;		// 카드의 폭  - 클래스 변수
	static int height = 250;	// 카드의 높이 - 클래스 변수
}

 

3.3 메서드

  • 메서드(method)는 특정 작업을 수행하는 일련의 문장을 하나로 묶은 것
  • 수학의 함수와 유사
  • 어떤 값을 입력 하면 이 값으로 작업 수행 후 결과를 반환

메서드 사용 이유

  • 높은 재사용성
  • 중복된 코드의 제거
  • 프로그램의 구조화

 

3.4 메서드의 선언과 구현

반환타입 메서드이름(타입 매개변수명1, 타입 매개변수명 ...){ //수행 문장;return 문; }

 

3.5 메서드의 호출

메서드 이름(값1, 값2)

  • main() 는 os에 의해 프로그램 실행 시 OS에 의해 자동적으로 호출
  • 인자(argument)와 매개변수(parameter) 는 순서,개수, 자료형이 일치 해야 함
  • static 메서는 같은 클래스 내의 인스턴스 메서드를 호출 할 수 없음
package ch06;
class MyMathTest {
	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(5, 3L) = "   + result4);
	}
}

class MyMath {
	long add(long a, long b) {
		long result = a+b;
		return result;
	//	return a + b;	// 위의 두 줄을 이와 같이 한 줄로 간단히 할 수 있다.
	}

	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;
	}
}

매개변수의 유효성 검사

double divide(double a, double b) {
		if(b == 0) {
			System.out.println("divide/zero");
			return 0;
		}
		return a / b;
	}

 

3.7 JVM의 메모리 구조

Method AreaCall Stack(호출 스택)Heap(힙)
클래스데이터(cv)main 함수 (lv)인스턴스(iv)

3.7.1 메서드 영역(method area)

  • 프로그램 실행 중 클래스가 사용되면 JVM은 해당 클래스(*.class)을 분석하여 클래스 정보 저장
  • 클래스의 클래스 변수(static 공용 변수)도 이 영역에 함께 생성

 

3.7.2 힙(heap)

  • 인스턴스가 생성되는 공간

 

3.7.3 call Stack(호출 스택)

  • 메서드가 호출되면 수행에 필요한 만큼의 메모리를 스택에 할당
  • 메서드 수행을 마치면 사용했던 메모리 반환하고 스택에서 제거
  • 호출스택의 제일 위에 있는 메서드가 현재 실행 중인 메서드
  • 아래에 있는 메서드가 바로 위의 메서드를 호출한 메서드
package ch06;
class CallStackTest2 {
	public static void main(String[] args) {
		System.out.println("main(String[] args)이 시작되었음.");
		firstMethod();
		System.out.println("main(String[] args)이 끝났음.");
	}

	static void firstMethod() {
		System.out.println("firstMethod()이 시작되었음.");
		secondMethod();
		System.out.println("firstMethod()이 끝났음.");		
	}

	static void secondMethod() {
		System.out.println("secondMethod()이 시작되었음.");
		System.out.println("secondMethod()이 끝났음.");		
	}
}


이전글

[JAVA] - chap 06 객체지향 프로그래밍 I(object-oriented programming I)_1