클래스(class) : 객체를 만들 때 필요한 설계도
객체(object) : 실제로 존재하는 것 → 클래스를 기준으로 여러 객체를 만들 수 있음
Person 클래스를 활용해 personA, personB 객체 생성
public class Main {
public static void main(String[] args) {
Person personA = new Person(); // ✅ 첫번째 객체 생성
Person personB = new Person(); // ✅ 두번째 객체 생성
}
}
Person 클래스 생성
public class Person() {
...
}
클래스의 구조 → 속성, 생성자, 기능
속성(property, field) : 객체의 속성(특징) 작성 → 변수로 표현
public class Person {
// 속성
String name;
int age;
String address;
}
public class Main {
public static void main(String[] args) {
// 객체 생성
Person personA = new Person();
Person personB = new Person();
// 객체를 통해 personA의 name 지정
personA.name = "seoyeon";
System.out.println(personA.name);
// 3. 객체를 통해 personB의 name 지정
personB.name = "lee";
System.out.println(personB.name);
}
}
생성자(constructor) : 객체를 어떻게 만들지 정의
특징 : 반환 자료형 X, 클래스명과 이름이 똑같음, 여러개 존재 가능
public class Person {
// 속성
String name;
int age;
String address;
// 생성자
// 기본생성자 자동추가
// Person() {}
Person(String name, int age) {
this.name = name; // this는 현재 실행 중인 객체를 가리킴
this.age = age; // this.name -> String name, name -> Person(name)
}
}
public class Main {
public static void main(String[] args) {
Person personA = new Person("seoyeon", 23);
Person personB = new Person(); // 생성자대로 지정하지 않았기에 에러
}
}
기능(메서드) : 원하는 기능 구현(원활한 관리를 위해 클래스와 관련된 기능 작성 추천)
public class Person {
// 속성
String name;
int age;
String address;
// 생성자
Person(String name, int age) {
this.name = name;
this.age = age;
}
// 기능 1 : 자기소개
void introduce() {
System.out.println("안녕하세요.");
System.out.println("나의 이름은 " + this.name + "입니다.");
System.out.println("나이는 " + this.age + "입니다.");
}
// 기능 2 : 더하기
int sum(int a, int b) {
int result = a + b;
return result;
}
}
public class Main {
public static void main(String[] args) {
Person personA = new Person("seoyeon", 23);
personA.introduce(); // personA 객체 introduce() 호출
Person personB = new Person("lee", 23);
int result = personB.sum(1, 2); // personB 객체 sum() 호출
System.out.println(result);
}
}
게터(getter) : 클래스의 속성을 가져올 때 사용되는 기능
public class Person {
// 속성
String name;
int age;
String address;
// 생성자
Person(String name, int age) {
this.name = name;
this.age = age;
}
// 게터 -> 메서드처럼 작동
String getName() {
return this.name; // 이름만 가져와서 반환해줌
}
}
public class Main {
public static void main(String[] args) {
Person personA = new Person("seoyeon", 23);
// personA의 이름만 가져와서 출력
String name = personA.getName();
System.out.println(name);
}
}
세터(setter) : 객체의 속성을 외부에서 설정
public class Person {
// 속성
String name;
int age;
String address;
// 생성자
Person(String name, int age) {
this.name = name;
this.age = age;
}
// 세터 -> 메서드처럼 작동
void setAddress(String address) {
this.address = address;
}
}
public class Main {
public static void main(String[] args) {
Person personA = new Person("seoyeon", 23);
// personA의 주소를 따로 설정
personA.setAddress("서울");
System.out.println(personA.address);
}
}
Method Area
Stack Area
Heap Area