자바
클래스와 객체
수아파파's
2023. 9. 14. 12:09
반응형
클래스는 객체를 생성하기 위한 템플릿이며,
객체는 클래스로부터 생성된 인스턴스를 의미합니다.
클래스는 변수와 메소드를 포함하는 데이터 타입으로, 멤버 변수와 메소드를 정의하는데 사용됩니다.
클래스를 정의하면 그 클래스를 통해 여러 개의 객체를 생성할 수 있습니다.
객체는 메모리에 할당된 인스턴스로, 클래스를 기반으로 생성됩니다.
즉, 클래스에서 정의한 변수와 메소드를 객체는 실제로 사용할 수 있습니다.
예를 들어, "사람"이라는 클래스를 정의하면 "이름"과 "나이"라는 변수와 "인사하기"라는 메소드를 포함할 수 있습니다.
그리고 이러한 클래스로부터 "철수"라는 객체와 "영희"라는 객체를 생성할 수 있습니다.
이렇게 생성된 객체는 각각 고유한 이름과 나이를 가지며, 객체의 메소드를 호출하여 독립적인 작업을 수행할 수 있습니다. 클래스와 객체를 사용하여 프로그램을 작성하면 데이터와 관련 메소드를 하나의 단위로 묶을 수 있으며,
이는 코드의 가독성과 재사용성을 높여줍니다.
public class Car {
private String brand;
private String model;
private int year;
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public void start() {
System.out.println("The car is starting.");
}
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Camry", 2021);
System.out.println("Brand: " + myCar.getBrand());
System.out.println("Model: " + myCar.getModel());
System.out.println("Year: " + myCar.getYear());
myCar.start();
}
}
Brand: Toyota
Model: Camry
Year: 2021
The car is starting.
반응형