케네스로그

[Java] 클래스 본문

Dev/Java

[Java] 클래스

kenasdev 2022. 2. 8. 18:37
반응형

클래스

클래스는 객체에 대한 프로토타입 또는 청사진이라고 할 수 있습니다.
객체는 속성(property)과 메소드(method)들을 지니며, 이것은 클래스를 통해 정의할 수 있습니다.

 

클래스를 정의하는 방법

  • 접근제어자(modifier)
    • public 또는 디폴트(default).
    • public인 경우, 어떠한 class에서든 접근할 수 있다
  • class 키워드
  • class 이름
    • class의 첫글자는 대문자로 시작한다
  • body
  • superclass: extends 키워드를 톨해 부모클래스를 명시
  • interface: 1개 이상의 인터페이스를 implements 키워드를 통해 명시
modifier class class_name extends super_class implements interfaces {
	// class ..
}

public class DemoClass extends Demo implements Mock_Class {
	// this is example
}

클래스의 이름은 반드시 대문자로 시작합니다.

 

 

클래스의 구성

  • 필드(field): 해당 클래스의 속성(attribute). 멤버 변수라고도 불린다.
  • 메소드(method): 해당 객체의 행동(behavior)를 나타낸다.
  • 생성자(constructor): 객체가 생성된 후 필드를 초기화
  • 초기화 블럭(initializer): static키워드가 붙은 초기화 블록으로, 조건/반복문등을 사용해서 초기화를 수행
    • 클래스 초기화 블록: 클래스 변수 초기화
    • 인스턴스 초기화 블록: 인스턴스 변수 초기화
class Class {               // 클래스
    String constructor;
    String instanceVar;     // 인스턴스 변수
    static String classVar; // 클래스 변수
		private int number;

    static {                // 클래스 초기화 블록
        classVar = "Class Variable";
    }

    {                       // 인스턴스 초기화 블록
    	instanceVar = "Instance Variable";
				this.number = 10;
    }

    Class() {                // 생성자
        constructor = "Constructor";
				this.number = 100;
    }

    void instanceMethod() {       // 인스턴스 메서드
        System.out.println(instanceVar);
    }

    static void classMethod() {   // 클래스 메서드
        System.out.println(classVar);
    }
}

public static void main(String[] args) {
	System.out.println(Class.number); // 10
	Class c = new Class();
	System.out.println(c.number); // 100
}

// 코드출처 https://jeeneee.dev/java-live-study/

 

💡 static 클래스 변수
static 클래스 변수는 static {} 과 같은 클래스 초기화 블록이 없거나 클래스 정의에서 초기값을 할당하지 않으면 기본값으로 할당됩니다. static 키워드가 붙은 클래스 멤버변수는 객체를 초기화하지 않더라도 접근하여 사용이 가능합니다.
참조사이트
https://www.infoworld.com/article/3040564/java-101-class-and-object-initialization-in-java.html

 

반응형