속성과 기능을 코드로 구현한 것속성 : 객체의 특성, 속성, 멤버 변수, property, attribute기능 : 메서드, 멤버 함수(접근제어자) class 클래스명 {
멤버변수;
메서드;
}
public class Student {
// 속성 : 멤버 변수
int studentId;
String studentName;
int grade;
String address;
// 기능 : 메서드
public void showStudentIdAndStudentName(){
System.out.println(studentId);
System.out.println(studentName);
}
public String getStudentName(){
return studentName;
}
public void setStudentName(String name){
studentName = name;
}
}
public static void main(String[] args){
// class 생성 (instance)
Student student1 = new Student();
// 값 할당
student1.studentId = 1;
student1.studentName = "이순신";
// 메서드 사용
student1.showStudentIdAndStudentName();
System.out.println(student1.getStudentName());
student1.setStudentName("홍길동");
student1.showStudentIdAndStudentName();
// 힙 메모리에 생성된 인스턴스의 주소값 출력
System.out.println(student1);
}
메서드는 클래스 내 멤버변수로 구현된 함수
함수반환타입 함수명 (매개변수타입 매개변수, ...){
...
return ___ ;
}
public class FunctionTest {
public static void main(String[] args){
int num1 = 10;
int num2 = 20;
int result = add(num1, num2);
System.out.println(result);
}
public static int add (int x, int y){
int result;
result = x + y;
return result;
}
}
클래스(static 코드) - 생성(인스턴스화) -> 인스턴스(dynamic memory)
클래스 변수이름 = new 생성자;
class : Doginstance : 아또, 두리, 등등Dog duri = new Dog();
int, StringDog변수명, durinew 키워드로 호출될때만 사용public class Student {
// 기본 생성자
// 따로 정의하지 않아도 jvm이 디폴트로 자동 생성
public Student(){
}
// 정의한 생성자
// 기본 생성자를 따로 정의하지 않은 경우, 매개 변수를 포함하여 생성해야 함
public Student(int id, String name){
studentId = id;
studentName = name;
}
// => 기본 생성자와 함께 정의한 경우, 둘다 사용 가능