728x90
반응형
객체 (Object)
클래스 변수를 객체 혹은 오브젝트라고 부른다.
클래스 변수를 선언할 때에는 new 키워드를 사용하여 동적으로 생성해 준다.
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String[] args) {
Box mybox = new Box();
}
}
인스턴스 변수 접근
객체가 실제로 사용될 때 이를 인스턴스(instance)라고 한다.
인스턴스 변수에 접근할 때에는 C++과 마찬가지로 dot 연산자를 사용한다.
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String[] args) {
Box mybox = new Box();
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
System.out.println("Volume is " + (mybox.width*mybox.height*mybox.depth));
}
}
이외에도 class 내부에서 함수 정의, this 연산자 등 class와 관련된 문법의 대부분은 C++과 동일하다.
728x90
반응형
'Java > Java 문법' 카테고리의 다른 글
[Java] 상속 (Inheritance), extends (0) | 2024.10.01 |
---|---|
[Java] 배열, Boundary Checking (경계 검사), 비대칭 배열 (0) | 2024.09.30 |
[Java] String, 문자열 비교, String Class 메서드 (0) | 2024.09.30 |
[Java] static method (정적 메서드), instance method (인스턴스 메서드) (0) | 2024.09.30 |
[Java] main 함수, 출력 (0) | 2024.09.18 |