3. 클래스 활용 - (1) 구성요소 활용

한승록·2023년 4월 25일
0

자바 활용

목록 보기
3/9
post-thumbnail

1) getter/setter

'getter''setter'private 처리된 필드 변수 에 접근하기 위해 사용됩니다.
getter는 해당 변수의 값을 그대로 반환시켜주는 함수입니다. 메서드를 public 처리하여 간접적으로 접근하는 것이죠.
이에 반해 setter는 전달 받은 데이터를 해당 멤버 필드 변수 에 저장해주는 것입니다.
class Drink {
	private String name;		// 이름은 private이므로 외부에서 접근할 수 없다
	private int price;
	private String[] nutritions;
	
	public Drink(String name, int price, String[] nutritions) {
		this.name = name;
		this.price = price;
		this.nutritions = nutritions;
	}
	
	public String getName() {	// 이름을 그대로 반환하는 메서드
		return name;			// 메서드 클래스 내부에 있어서 접근이 허용된다
	}							// 메서드 public이므로 외부에서 호출할 수 있다
	
	public void setName(String name) {	// 전달받은 이름을 필드에 저장하는 메서드
		this.name = name;				// 메서드는 클래스 내부에 있어서 대입이 허용
	}									// 메서드는 public이므로 외부에서 호출 가능
	
	public int getPrice() {
		return price;
	}
	
	public void setPrice(int price) {	// 객체 생성 이후에도, 값을 자유롭게 바꿀수 있다
		this.price = price;
	}
	
	public String[] getNutritions() {
		return nutritions;
	}
}


public class Ex01_Getter_Setter {
	public static void main(String[] args) {

//		Drink ob1 = new Drink();
//		ob1.name = "코카콜라";	// 바로 접근은 private때문에 불가능
//		ob1.price = 2000;
//		ob1.getNutritions = {"열량 : 112kcal", "탄수화물 : 28g", "당류 : 27g", "나트륨 : 15mg"};
		
		String[] nutr_coke = new String[]{"열량 : 112kcal", "탄수화물 : 28g", "당류 : 27g", "나트륨 : 15mg"};
		Drink ob1 = new Drink("코카콜라", 2000, nutr_coke);
		
		ob1.setName("코카콜라 250ml");
		ob1.setPrice(880);
//		ob1.setNutitions(nutr_coke);
//		setter를 작성하지 않았기 때문에, 객체 생성 이후 값을 변경할 수 없게 된다
		
		System.out.println("상품이름 : " + ob1.getName());
		System.out.println("상품가격 : " + ob1.getPrice());
		System.out.println("영양성분표 : " + ob1.getNutritions());
		
	}
}




2) static

일반적인 필드는 객체에 소속되기 때문에 객체마다 서로 다른 값을 저장할 수 있습니다.
하지만 static 속성의 필드는 클래스에 고정된 형태로 해당 다른 객체라도 해당 속성을 공유하게 됩니다.
또다른 속성으로는 staticstatic 에서 non-staticnon-static 끼리 상호작용 가능합니다.
class Test1 {
	String name;
	static int countOfEyes = 2;	// static은 기울임꼴로 표현합니다
	
	public String getName() {
		return name;
	}
	
	public static int getCountofEyes() {
		return countOfEyes;
	}
	
	static void test2() {	// 클래스 소속
		System.out.println(countOfEyes);
		
		// System.out.println(name);
		// Cannot make a static reference to the non-static field name
		
		// test3();
		// Cannot make a static reference to the non-static method test3() from the type Test1
		
		// static은 static끼리, non-static은 non-static끼리 참조
	}
}

public class Ex03_Static {
	public static void main(String[] args) {		
		// static 속성의 메서드는 클래스에 고정된 형태이기 때문에
		// 객체를 생성하지 않고, 클래스에서 바로 메서드를 호출할 수 있게 됩니다
		
		// static 요소는 객체를 생성하지 않아도 접근할 수 있습니다
		System.out.println(Test1.countOfEyes);			// static field 참조
		System.out.println(Test1.getCountofEyes());		// static method 호출
		
		// non-static요소는 객체를 통해서 접근해야 참조 및 호출할 수 있습니다
		// Cannot make a static reference to the non-static field Test1.name
//		System.out.println(Test1.name);
		
		Test1 ob = new Test1();
		System.out.println(ob.name);		// 객체의 필드
		ob.name = "홍길동";
		System.out.println(ob.getName());	// 객체의 메서드
		
		// 객체가 생성되었다면 클래스는 이미 로드된 상황이므로 객체를 통해서 static 요소에 접근가능
		// 그러나 권장되는 방법은 아닙니다(static은 static끼리, non-static은 non-static끼리)
		
		// The static field Test1.countOfEyes should be accessed in a static way
		System.out.println(ob.countOfEyes);
		System.out.println(Test1.countOfEyes);
	}
}
보시다시피 static 속성의 요소non-static 속성의 요소가 있다면 클래스 로드 시점에서 static 요소가 생성되고 객체를 생성해야 non-static 요소가 생성 됩니다
따라서 static 요소는 non-static을 참조할 수 있으나 non-static 요소는 static을 참조할 수 없습니다



3) final

final class A {
	int num1 = 10;
	final int num2 = 20;
	static int num3 = 30;
	static final int num4 = 40;
    
   	A() {
		num1 += 5;
		num2 += 5;
		num3 += 5;
		num4 += 5;
	}
}

public class Velog {
	public static void main(String[] args) {
 
 	A a = new A();
	System.out.println("int num1에 '+= 5'를 산수한 값 : " + a.num1);
	System.out.println("final int num2에 '+= 5'를 산수한 값 : " + a.num2);
	System.out.println("static int num3에 '+= 5'를 산수한 값 : " + a.num3);
	System.out.println("static final int num4에 '+= 5'를 산수한 값 : " + a.num4);
 
    }
}
위의 코드에서 n1, n2, n3, n4 는 전부 정상적으로 실행이 이루어질까요?
final은 마지막이라는 뜻에 어울리게 변경할 수 없도록 하는 상태를 말합니다.
그렇기 때문에 다음과 같은 결과를 도출하게 됩니다.

<※ 결과는 다음과 같습니다.>

해당 에러메시지는 결과적으로 final 변수들에 대한 대입연산자를 실행하지 못하였다는 의미와 동일합니다. 그럼 마지막으로 final에 대해 상기시켜 드리도록 하겠습니다. 이번 포스트를 정리해볼까 합니다.
final 필드 는 값을 변경할 수 없습니다. 따라서 초기값을 반드시 지정해야만 합니다.
final 메서드 는 오버라이딩 할 수 없습니다.
final 클래스는 상속받을 수 없습니다. 따라서 기존 만들어진 클래스를 그대로 활용해야 합니다.
profile
개발 학습

0개의 댓글