클래스 : 클래스는 객체를 생성하기 위한 설계도 또는 청사진이라고 할 수 있다
즉 자료형 측면에서 보면 새로운 자료형을 만드는 도구이다
클래스는 객체의 구조와 동작 방식을 정의하고, 이를 통해 여러 객체가 동일한 속성과 행동을 가지도록 한다
public class Person {
private String name;
private int age;
// 생성자
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// greet 메서드
public void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// have_birthday 메서드
public void haveBirthday() {
this.age += 1;
System.out.println("Happy birthday " + name + "! You are now " + age + " years old.");
}
위에 예시 처럼 객체(Object)를 상태정보(멤버변수)와 행위정보 (멤버메서드)를 뽑아서 설계할 수 있게 해주는 도구가 클래스이다
여기서 Person 클래스는 name, age 라는 두개의 속성과 greet(), haveBirthday()라는 행동을 나타내는 메소드를 정의하고 있다.
인스턴스는 클래스에서 생성된 구체적인 객체, 클래스의 구조를 실제로 메모리에 할당하여 사용 가능한 상태로 만든 것
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);
person1.greet(); // 출력: Hello, my name is Alice and I am 30 years old.
person2.greet(); // 출력: Hello, my name is Bob and I am 25 years old.
person1.haveBirthday(); // 출력: Happy birthday Alice! You are now 31 years old.
person1.greet(); // 출력: Hello, my name is Alice and I am 31 years old.
}
}
// 인스턴스 생성
Person person1 = new Person();
Person person2 = new Person();
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);
person1.greet(); // 출력: Hello, my name is Alice and I am 30 years old.
person2.greet(); // 출력: Hello, my name is Bob and I am 25 years old.
person1.haveBirthday(); // 출력: Happy birthday Alice! You are now 31 years old.
person1.greet(); // 출력: Hello, my name is Alice and I am 31 years old.
클래스: 객체를 생성하기 위한 설계도
인스턴스: 클래스에서 생성된 구체적인 객체
각 인스턴스는 클래스의 구조를 실제로 메모리에 할당하여 사용 가능한 상태로 만든 것
-> 클래스는 추상적인 개념이며 실제 작업을 수행할 수 없기 때문에 인스턴스는 이러한 클래스의 정의를 바탕으로 생성되어 실제 프로그램에서 작업을 수행하는 주체가 된다
-> 클래스와 인스턴스 개념을 이해하고 활용하면, 코드의 재사용성과 유지보수성을 향상 시킬 수 있음
박매일님의 자바강의