Java의 주요 키워드: this, static, super, final
Java는 객체 지향 프로그래밍 언어로, 다양한 키워드를 통해 코드를 구조화하고 관리한다. 이 글에서는 그동안 헷갈렸던 this, this(), static, super, super() 키워드에 대해 예시를 통해 정리해보겠습니다.
1. this 키워드
this 키워드는 자기 자신의 객체를 참조하는 변수다. 주로 클래스 내에서 인스턴스 변수와 메서드를 호출할 때 사용된다. this 키워드는 현재 객체를 가리키며, 동일한 클래스 내의 다른 메서드를 호출하거나 인스턴스 변수를 사용할 때 유용하다.
public class Example {
private int value;
public Example(int value) {
this.value = value; // 인스턴스 변수와 파라미터를 구분하기 위해 사용
}
public void display() {
System.out.println("Value: " + this.value);
}
}
2. this() 메서드
this()는 생성자 내부에서만 사용 가능한 메서드로, 같은 클래스 내의 다른 생성자를 호출할 때 사용된다. 생성자 오버로딩을 통해 코드의 중복을 줄이고, 보다 간결한 초기화를 가능하게 한다.
public class Example {
private int value;
private String text;
public Example(int value) {
this(value, "default"); // 다른 생성자 호출
}
public Example(int value, String text) {
this.value = value;
this.text = text;
}
public void display() {
System.out.println("Value: " + this.value + ", Text: " + this.text);
}
}
3. static 키워드
static 키워드는 클래스 레벨에서 멤버를 정의할 때 사용된다. static 키워드를 선언하면, 해당 멤버는 인스턴스가 아닌 클래스 자체에 속하게 된다. 따라서 모든 인스턴스가 동일한 값을 공유한다. static 키워드는 메서드에도 적용되어, 클래스의 인스턴스를 생성하지 않고도 호출할 수 있다.
public class Example {
public static int count = 0;
public Example() {
count++; // 모든 인스턴스가 공유하는 변수
}
public static void displayCount() {
System.out.println("Count: " + count);
}
}
자주 Java에서 쓰이던 Arrays클래스의 메소드 중 하나인 Arrays.sort()의 경우에도 sort가 static 메소드이기 때문에 인스턴스를 선언하지 않고 바로 매개변수로 배열을 넣어 사용했다.
public class Main {
public static void main(String[] args) {
}
}
우리가 익히 알고 무심고 사용하던 위 main 코드에서도static 메소드가 쓰인다. 위 코드의 역할은 먼저 파일명과 동일한 이름의 public class를 실행하고 그 class 에서 main이라는 이름의 static 메소드를 찾아 실행하는 것이다. main 메소드는 멤버 메소드일 필요가 없다. 주로 Arrays 와 같은 util 클래스들은 정적 메소드들을 많이 사용한다.
4. super 키워드
super 키워드는 부모 클래스의 인스턴스를 참조하는 변수다. 자식 클래스에서 부모 클래스의 변수나 메서드를 호출할 때 사용된다. 주로 부모 클래스의 메서드를 오버라이드하면서, 부모 클래스의 메서드도 호출하고자 할 때 사용된다.
public class Parent {
public void display() {
System.out.println("Parent Display");
}
}
public class Child extends Parent {
public void display() {
super.display(); // 부모 클래스의 메서드 호출
System.out.println("Child Display");
}
}
5. super() 메서드
super()는 자식 클래스의 생성자에서 부모 클래스의 생성자를 호출할 때 사용된다. 자식 클래스의 생성자가 호출될 때, 먼저 부모 클래스의 생성자가 호출되어야 한다. 이는 객체 초기화 과정에서 부모 클래스의 초기화가 먼저 이루어져야 함을 의미한다.
public class Parent {
private int value;
public Parent(int value) {
this.value = value;
}
}
public class Child extends Parent {
private int childValue;
public Child(int value, int childValue) {
super(value); // 부모 클래스의 생성자 호출
this.childValue = childValue;
}
}
6. final 키워드
final 키워드는 변수, 메서드, 클래스에 적용될 수 있으며, 각각의 용도에 따라 다른 의미를 가진다.
변수에 사용될 때:
- final 변수는 한 번 초기화된 후에 값을 변경할 수 없다. 이는 상수와 같은 역할을 한다.
public class Example {
public final int MAX_VALUE = 100;
public void display() {
System.out.println("Max Value: " + MAX_VALUE);
}
}
메서드에 사용될 때:
- final 메서드는 서브클래스에서 오버라이드할 수 없다.
public class Parent {
public final void show() {
System.out.println("This is a final method.");
}
}
public class Child extends Parent {
// 이 메서드는 오버라이드할 수 없다.
}
클래스에 사용될 때:
- final 클래스는 서브클래스가 될 수 없다. 즉, 상속할 수 없는 클래스가 된다
public final class FinalClass {
public void display() {
System.out.println("This is a final class.");
}
}
// 아래 코드는 컴파일 에러를 발생시킨다.
// public class SubClass extends FinalClass {}
위와 같은 Java의 this, this(), static, super, super() 키워드는를 적절히 사용함으로써 코드의 가독성과 재사용성을 높이고, 보다 효율적인 프로그램을 작성할 수 있다.