클래스는 설계도, 객체는 설계도를 따라 만든 완성품이다.
new 키워드를 통해 런타임에 객체를 생성할 수 있다.
명시적으로 객체 메모리를 해제할 수 없으며, GC가 객체의 수명을 관리한다.
예시
class Student {
String name;
int age;
int score;
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
// Student: 클래스
// student: 객체
student.name = "김하나";
student.age = 20;
student.score = 87;
System.out.println(student.name);
System.out.println(student.age);
System.out.println(student.score);
}
}
생성자는 클래스를 만드는 방법을 정의한다.
예시
class Student {
String name;
int age;
int score;
Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
}
Java의 메서드는 클래스 내부에만 존재한다.
디폴트 파라미터는 지원하지 않는다.
public class 클래스이름 {
[반환자료형] [메서드이름](매개변수..) {
작업 명령문들...
}
}
예시
class Student {
String name;
int age;
int score;
Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
public void printInfo() {
System.out.println(name + " / " + age + "세 / " + score + "점");
}
}