new라는 키워드를 사용하며 객체를 만드는 과정을 인스턴스화 라고 표현한다.1. 속성, 2. 생성자, 3. 기능 부분으로 나누어진다.class 클래스 {
// 1. 속성
// 2. 생성자
// 3. 기능
}
객체가 담긴 변수.속성으로 접근한다.public class Main {
public static void main(String[] args) {
// 1. 객체 생성
Person personA = new Person();
Person personB = new Person();
// 2. ✅ 객체를 통해 접근 personA 의 name
System.out.println(personA.name);
// 3. ✅ 객체를 통해 접근 personB 의 name
System.out.println(personB.name);
}
}
✅ 생성자를 활용해
Person객체 만들기
public class Person {
String name;
int age;
String address;
Person() {} // ❌ 기본생성자 제거됨
Person(String name, int age) { // ✅ 새로운 생성자(조립설명서)
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person personA = new Person("gygim", 10); // ✅ 조립설명서 준수
Person personB = new Person("Steve", 5); // ✅ 조립설명서 준수
}
}
✅
this키워드
this는 객체 자신을 가리키는 키워드이며 현재 실행 중인 객체를 의미한다.
class Person {
...
// ✅ 사람의 소개 기능
void introduce() {
System.out.println("안녕하세요.");
System.out.println("나의 이름은 " + this.name + "입니다.");
System.out.println("나이는 " + this.age + "입니다.");
}
// ✅ 사람의 더하기 기능
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("gygim", 10);
personA.introduce(); // ✅ personA 객체 introduce() 호출
Person personB = new Person("Steve", 5);
}
}
String getName() {
return this.name;
}
int getAge() {
return this.age;
}
String getAddress() {
return this.address;
}
String name = person.getName();
int age = person.getAge();
String address = person.getAddress();
void getName(String name) {
this.name = name;
}
void getAge(int age) {
this.age = age;
}
void setAddress(String address) {
this.address = address;
}
public class Main {
public static void main(String[] args) {
Person personA = new Person("gygim", 20);
Person personB = new Person("Steve", 15);
personA.setAddress("서울"); // ✅ personA 의 주소 설정
personB.setAddress("미국"); // ✅ personA 의 주소 설정
}
}