
class Car {
String color; // 속성(필드)
void drive() { // 동작(메소드)
System.out.println("Driving...");
}
}
int sum = calc.add(3, 5); // 메소드 호출
public 가능.public class Student {
String name;
int age;
void study() {
System.out.println(name + " is studying");
}
}
new 연산자로 객체 생성 → 힙(heap)에 저장, 스택(stack)에는 참조 주소 저장
클래스 용도
main() 보유, 실행 가능Student s1 = new Student(); // new 사용
참조변수.필드로 접근Car myCar = new Car();
myCar.color = "red"; // 필드 접근
new → 생성자 호출 → 객체 초기화 → 참조값 반환class Car {
String model;
Car(String model) {
this(model, "은색", 250); // 다른 생성자 호출
}
Car(String model, String color, int speed) {
this.model = model;
}
}
리턴타입 메소드명(매개변수) { ... }참조변수.메소드()int sum(int... values) {
int result = 0;
for (int v : values) result += v;
return result;
}
class Counter {
int count; // 인스턴스 멤버
static int total; // 정적 멤버
}
static 키워드로 선언, 클래스에 고정됨.클래스명.멤버 형태로 사용.class Util {
static int add(int a, int b) {
return a + b;
}
}
int result = Util.add(5, 3);
class Config {
static String info;
static {
info = "Setting Loaded";
}
}
this 사용 불가좋습니다 👍 이번에 주신 6.11 ~ 6.15(final 필드, 패키지, 접근제한자, Getter/Setter, 싱글톤 패턴) 부분도 이전과 동일하게 요약 중심 + 코드 예제 보강으로 정리해드렸습니다.
인스턴스/정적)는 값 변경 가능 → 경우에 따라 수정 불가 필드 필요final 사용 시 값이 한 번 저장되면 수정 불가초기화 방법
class Car {
final String model;
Car(String model) { // 생성자 초기화
this.model = model;
}
}
static final)class Earth {
static final double RADIUS = 6400; // 단위: km
}
com.company.project)package com.mycompany.project;
import 패키지명.*; → 하위 패키지 포함 ❌import com.hankook.Tire; // 특정 클래스
import com.hankook.*; // 동일 패키지 내 모든 클래스
com.hankook.Tire tire = new com.hankook.Tire();
| 제한자 | 클래스 | 패키지 | 자식 클래스 | 전체 |
|---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
| (default) | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |
public, default만 가능public, protected, default, private 모두 가능private 필드 사용class Member {
private String name;
public String getName() { // Getter
return name;
}
public void setName(String n) { // Setter
this.name = n;
}
}
private으로 막음public class Singleton {
// private 정적 필드, 한 번만 로딩됨
private static final Singleton instance = new Singleton();
private Singleton() {} // private 생성자
public static Singleton getInstance() {
return instance;
}
}
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // true (동일 객체)