oop(1)에서 다룬 마지막 내용에 접근 제어자를 설명하면서
getter랑 setter를 잠깐 언급을 했었습니다
그럼 getter랑 setter는 뭐냐?
private처리한 필드는 외부에서는 접근할 수 없고, 클래스 내에서는 접근 할 수 있으므로
클래스 내의 메서드를 이용해서 간접적으로 그 필드 값을 얻거나 새로운 값을 넣어주는데
외부에서 간접적으로 필드에 접근하게 할 수 있는 메서드를 getter와 setter라고 합니다
ex) 값을 보여주고 싶지만, 필드는 건드리게 하고 싶지 않을때
-> getter만 적어줌
import java.util.Arrays;
class Drink{
private String name;
private int price;
private String[] nutritions;
// 생성자
public Drink(String name, int price, String[] nutritions){
this.name = name;
this.price = price;
this.nutritions = nutritions;
}
// getter, setter
public String getName() {
여기서 Getter와 Setter가 들어간 Beans개념이 등장한다
자바 빈즈란, 여러 자바 기반 플랫폼에서 객체를 나타내기 위한 클래스의 기본형식이다
class Member{
// 1) 필드는 private로 구성한다
private String name;
private int age;
// 2) 생성자는 public 으로 구성한다
// 3) 생성자는 기본생성자를 반드시 포함해야 한다
public Member(){}
public Member(String name, int age){
this.name = name;
this.age = age;
}
// 2) 메서드는 public으로 구성한다(기본적)
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
물론, 클래스의 필드값을 참조시키고 싶은 의도가 있다거나 메서드에 제한을 거는 등의 개발자 임의의 처리는 있을 수 있다. 그러나 대부분 자바 빈즈라고 하면 이렇게 구성된다!
static이라는 것은 크게는 클래스에 고정된 형태를 말한다
종류로는 static 변수, static메서드 같은 것들이 있지만 개념을 제대로 잡는 것이 좋다
class Human{
// non-static field
private String name;
// static field
private static int countOfEyes = 2;
// non-static method
public String getName(){
return name;
}
// static method
public static int getCountOfEyes(){
return countOfEyes;
}
}
class Example{
public static void main(String[] args){
//인스턴스를 생성하지 않고는 메서드가 실행이 안됨
//System.out.println(getName());
//인스턴스 없이 클래스 자체로 불러와도 실행이 됨
System.out.println(Human.getCountOfEyes());
// = 2
}
}
static 요소의 특징이라고 하면
java를 실행시 컴퓨터의 입장에서
먼저 class를 실행을 하고 그 class를 로드하는 시점에서 static 요소가 생성되고
객체를 생성해야(인스턴스) 클래스에서 non -static메서드를 가져올 수 있다
그 말은, static 메서드나 필드는 앞에 클래스명을 붙혀서 객체생성 없이 가져올 수 있다
그래서 static 요소는 non-static을 참조할 수 있으나
non-static 요소는 static요소를 참조할 수 없다
class Human{
// non-static field
private String name;
// static field
private static int countOfEyes = 2;
// non-static method
public String getName(){
return name;
}
// static method
public static int getCountOfEyes(){
return countOfEyes;
}
}
class Example{
public static void main(String[] args){
// non-static 요소는 객체를 통해서만 참조 가능
Human ob1 = new Human();
ob.name = "이지은";
System.out.println(ob.getName());
// -> 이지은
// 그러나, 객체가 생성되었다면 클래스가 생성되었다는 뜻이므로 객체를 이용해서
// static 요소에 접근 할 수 있다
System.out.println(ob1.getCountOfEyes());
// -> 2
// 그러나 위처럼 접근하면
// The static field Test1.countOfEyes should be accessed in a static way
// 빨간 밑줄 까진 아니지만 노란 밑줄로 위와 같이 뜬다
System.out.println(Human.getCountOfEyes());
// 이렇게 쓰는게 좋다
}
위와 같이 static요소를 객체 생성을 통해서 참조를 할 수 있으나, static은 클래스를 이용해서 static끼리, non-static은 객체를 생성해서 객체를 통해서 참조하는 것이 좋다
final은 변경할 수 없다. 마지막 값, 내용이라는 뜻으로 사용된다.
final class A{
int n1 = 10;
final int n2 = 20; // final이 들어가면 무조건 초기값을 줘야됨 (변경 불가능하기 떄문에)
static int n3 = 30; // final과 static final의 차이
static final int n4 = 40; // final 필드라면 객체를 생성할때 생성자로 매개변수로 받아 생성할 수 있지만
// static final은 클래스가 만들어질때 더이상 변경이 불가능하므로 무조건!
// 필드 생성시 초기화 해야한다!
// public static final int NUMBER_4 = 40;
// java에서 오로지 static final만 변수명을 다 대문자로 쓰고, 구분은 _로 한다
A(){
n1 += 5;
// n2 += 5; // final 필드는 값을 변경할 수 있다
n3 += 5;
// n4 += 5; // static final 필드도 값을 변경할 수 없다
}
}
class B /*extends A*/{ // The type B cannot subclass the final class
// final 클래스 A의 서브클래스가 될 수 없습니다
// final 클래스는 상속받을 수 없다
void test1() {
System.out.println("test1");
}
final void test2() {
System.out.println("test2");
}
}
class C extends B {
@Override
void test1( ) {
System.out.println("test3");
}
// @Override // Cannot override the final method from B
// void test2() { // final 메서드는 오버라이딩 할 수 없다
//
// }
}
public class Ex05_Final {
public static void main(String[] args) {
int num1 = 10;
final int num2 = 20;
num1 += 1;
// num2 += 2;
// The final local variable num2 cannot be assigned.
// It must be blank and not using a compound assignment
// final 지역변수 num2는 할당(대입)할 수 없습니다
// 대입을 사용하지 않아야 합니다
System.out.println(num2); // 값을 변경하지 않는다면 출력에는 전혀 문제 없음
}
}
// 1)
// TV 의 객체를 상상하면서
// 클래스를 구성하세요
// 객체의 속성은 필드로 표현합니다
// 객체의 기능은 메서드로 표현합니다
// 실질적으로 보이는 코드는 Main class에
// 볼륨 업, 다운, 채널 업 , 다운, 전원 켜기 끄기의 기능들은 TV class에 구성하세요
// 필드는 보통 공개되지 않습니다 (private)
// 메서드는 보통 공개되어 있습니다 (public)
// 2)
// 자판기(vendingMachine)의 객체를 상상하면서
// 클래스를 구성하세요
// 실질적으로 보이기 위한 코드는 Main class에
// 제품의 이름 및 가격을 포함한 Product class
// 자판기의 기능을 담당하는 Machine class에 나눠서 구성하세요
// 필드는 보통 공개되지 않습니다 (private)
// 메서드는 보통 공개되어 있습니다 (public)