7. final 접근 지정자
`final` 접근 지정자는 해당 멤버 또는 클래스를 수정할 수 없도록 지정합니다. 다음은 `final` 접근 지정자의 사용 예제입니다.
7.1. final 필드
class Circle {
private final double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
}
`radius` 필드를 `final`로 선언하면, 객체가 생성된 후에는 값을 변경할 수 없습니다. 이것은 불변(Immutable) 객체를 생성하는 데 활용됩니다.
7.2. final 메서드
class Parent {
final void finalMethod() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// 오버라이딩 불가능
// void finalMethod() { ... }
}
`final` 메서드는 하위 클래스에서 오버라이딩할 수 없습니다. 이를 통해 메서드의 구현을 변경하지 못하도록 제한할 수 있습니다.
7.3. final 클래스
final class FinalClass {
// ...
}
// 하위 클래스 생성 불가
// class SubClass extends FinalClass { ... }
`final` 클래스는 다른 클래스에서 상속할 수 없습니다. 이것은 특정 클래스의 확장을 방지하고, 안정성을 높이는 데 사용됩니다.
8. static 접근 지정자
`static` 접근 지정자는 클래스의 멤버를 클래스 수준으로 만들어줍니다. 즉, 클래스의 모든 인스턴스가 공유하는 멤버를 정의하는 데 사용됩니다. `static` 멤버는 클래스의 인스턴스 생성 없이 사용할 수 있습니다.
8.1. static 필드
class MathUtil {
static final double PI = 3.141592653589793;
static int add(int a, int b) {
return a + b;
}
}
`static` 필드 `PI`는 클래스 수준에서 공유되며, `static` 메서드 `add`는 인스턴스 생성 없이 호출할 수 있습니다.
double circleArea = MathUtil.PI * Math.pow(radius, 2);
int sum = MathUtil.add(5, 3);
8.2. static 메서드
class StringUtils {
static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
}
`static` 메서드 `isEmpty`는 클래스 수준에서 호출 가능하며, 인스턴스를 생성하지 않고도 사용할 수 있습니다.
boolean empty = StringUtils.isEmpty(input);
9. protected 접근 지정자와 super 키워드
`protected` 접근 지정자는 상속 관계에서 중요한 역할을 합니다. 하위 클래스에서 상위 클래스의 `protected` 멤버에 접근하려면 `super` 키워드를 사용해야 합니다.
class Animal {
protected void makeSound() {
System.out.println("동물 소리");
}
}
class Dog extends Animal {
void bark() {
System.out.println("멍멍!");
}
void animalSound() {
super.makeSound(); // 상위 클래스의 protected 메서드 호출
}
}
`Dog` 클래스의 `animalSound` 메서드에서 `super.makeSound()`를 통해 상위 클래스인 `Animal` 클래스의 `makeSound` 메서드를 호출하고 있습니다. 이를 통해 상위 클래스의 메서드를 활용할 수 있습니다.
'JAVA' 카테고리의 다른 글
Java 람다 알아보자 (2) | 2024.06.02 |
---|---|
Java for문에 대해서 알아보자 (0) | 2023.10.15 |
Java 접근지정자 알아보자 1편 (0) | 2023.10.07 |
Java 인터페이스 알아보자 (0) | 2023.10.02 |
Java 추상클래스 를 알아보자 (0) | 2023.09.24 |