java

실습) 클래스 생성, 호출

dalc3154 2025. 2. 21. 16:18

=== 문제 1. 클래스 생성 ===
아래의 요구사항에 따라 Person 클래스를 작성

- Person 클래스는 이름(name)과 나이(age)를 저장하는 인스턴스 변수를 가짐
- 기본 생성자를 포함하고, 이름과 나이를 초기화하는 생성자를 추가
- introduce() 메서드를 추가하여 "안녕하세요, 저는 [이름]이고, [나이]살입니다."라는 문장을 출력

=== 문제 2. 객체 생성 및 메서드 호출 ===
Person 클래스를 사용하여 다음과 같은 동작을 수행하는 코드를 작성

- 이름이 "홍길동", 나이가 25인 Person 객체를 생성
- 생성된 객체의 introduce() 메서드를 호출하여 자기소개를 출력

=== 문제 3. 클래스 변수 ==
Person 클래스에 다음 요구사항을 추가

- population이라는 정적 변수(클래스 변수)를 추가하고, 생성된 Person 객체의 수를 저장
- 각 객체가 생성될 때마다 population 변수를 증가시키도록 생성자를 수정

class Person{
	String name;
	int age;
	
	Person(){
		population++;
	}
	
	Person(String name, int age){
		this.name = name;
		this.age = age;
		population++;
	}
	
	void introduce() {
		System.out.println("안녕하세요, 저는 " + name + "이고, " + age + "살입니다.");
	}
	 static int population = 0;
	 
}

public class H_Practice {
	public static void main(String[] args) {
		
		Person hong = new Person();
		hong.name = "홍길동";
		hong.age = 25;
		hong.introduce();
		
		System.out.println(Person.population);// 1
		
		new Person();
		new Person();
		new Person();
		new Person();
		new Person();
		System.out.println(Person.population);// 6
	}
}