클래스 생성 및 인스턴스화
2024. 3. 26. 02:55ㆍJava
- 자바에서 클래스는 설계도
- 클래스에는 객체를 생성하기 위한 필드와 메소드가 정의되어 있어야함
- 클래스로부터 만들어진 객체를 해당 클래스의 인스턴스라고 함
- 클래스로부터 객체를 만드는 과정을 인스턴스화라고 함
- 하나의 클래스로부터 여러 객체를 만들 수 있음
- 클래스 선언
- 클래스 선언 방법
public class 클래스명 { }
- Dice 클래스와 클래스의 필드 및 메소드 선언
public class Dice { private int face; private int eye; public void roll(){ eye = (int)(Math.random()*face) + 1; } public int getEye(){ return eye; } public void setFace(int face) { this.face = face; } }
- 객체 선언
- 객체 선언 방법
클래스명 객체명 = new 클래스명();
- DiceTest 클래스에서 Dice 클래스 객체 생성
package com.example.main; import com.example.util.Dice; public class DiceTest { public static void main(String[] args) { Dice dice = new Dice(); dice.setFace(6); dice.roll(); int eye = dice.getEye(); System.out.println(eye); } }
'Java' 카테고리의 다른 글
인터페이스(Interface) (0) | 2024.04.16 |
---|---|
추상 클래스 (0) | 2024.04.16 |
접근제한자 (0) | 2024.03.26 |
final 키워드 (0) | 2024.03.26 |
매개변수와 전달인자 (0) | 2024.03.26 |