클래스
데이터 저장 단계
1) 변수(데이터 저장 공간) : 하나의 데이터. 하나의 타입(int, String 등)이 들어갈 수 있다.
2) 배열 : n개의 데이터. 하나의 공간.
3) 구조체(자바에서는 없음) : n개의 데이터. n개의 타입. 하나의 묶음에서 다른 데이터 타입을 가질 수 있는 것.
4) 클래스 : n개의 데이터. n개의 타입 + 기능(로직 = 메서드)
클래스 선언 방법
// 클래스 선언.
class Student {
// 클래스 변수
// String schoolName; -> static, 초기화
static String schoolName = "한국대학교";
// 필드.
// 인스턴스 변수
String studentNumber;
String name;
int age;
String telNumber;
String course;
String grade;
// 클래스 메서드 :
static void startVacation() {
// System.out.println(name + "방학시작!!"); // Cannot make a static reference to the non-static field name
System.out.println("방학시작!!");
}
// 인스턴스 메서드
void study() {
System.out.println(course + "를(을) 공부한다.");
}
void test() {
System.out.println(course + "를(을) 시험친다.");
}
void sleep() {
System.out.println("잠을 잔다.");
}
}
객체
public static void main(String[] args) {
// student 인스턴스 생성 .
Student gildong = new Student();
// 데이터 할당
// gildong.schoolName = "한국대학교";
gildong.studentNumber = "1223020";
gildong.name = "홍길동";
gildong.age = 24;
gildong.telNumber = "010-1234-5678";
gildong.course = "경영학";
gildong.grade = "A+";
gildong.study();
gildong.test();
gildong.sleep();
Student chulsoo = new Student();
chulsoo.studentNumber = "2323110";
chulsoo.name = "김철수";
chulsoo.age = 20;
chulsoo.telNumber = "010-1111-2222";
chulsoo.course = "회계원리";
chulsoo.grade = "B+";
chulsoo.test();
System.out.println(gildong.name);
System.out.println(chulsoo.name);
// 각각의 인스턴스는 독립적인 속성을 가지고 있다.
// 독립적인 속성 = 인스턴스 변수
gildong.name = "홍동길"; // 이름 변경.
System.out.println(gildong.name);
System.out.println(chulsoo.name);
// 철수에게 지정하지 않아도 스쿨네임이 학교 이름이 찍혀있다.
System.out.println(gildong.schoolName); // 길동이에 스쿨네임을 넣지 않아도 잘 나온다.
System.out.println(chulsoo.schoolName);
// System.out.println(Student.age); // Cannot make a static reference to the non-static field Student.age
System.out.println(Student.schoolName); // 클래스를 선언할 때 초기화를 같이 해준다.
// Student.study(); // Cannot make a static reference to the non-static method study() from the type Student
Student.startVacation();
}
}
클래스 예제
계산기 코드
class MyMath {
static final double PIE = 3.14;
static double frustumOfACone(double r1, double r2, double h) {
double result = (PIE * h * (r1* r1 + r1 * r2 + r2 * r2)) / 3;
return result;
}
static double rightCircularConeV(double r, double h) {
double result = (PIE * r * r * h) / 3;
return result;
}
}
public class ClassAndObject { // 클래스 선언. public 접근제어자
/*
* method (메서드) == function (함수)
* 수학 문제를 메서드로 만드는 연습을 하는게 좋음
* x + 2 = f(x) (단, x는 정수이다)
*/
// void f(int x)/*(데이터 값 제한)*/ { // return 오류가 나기 때문에. 반환타입을 void에서 int로 바꿈.
int f(int x) {
int y = x + 2;
return y; // 오류) Void methods cannot return a value 반환타입에 어떻게 내보낼지 적어줘야 한다.
}
double add(double a, double b) { // 더하기 연산자. 더하기 연산기능.
double result = a + b;
return result; // 반환 타입을 지정 해 주어야 사용할 수 있다.
}
// String operator 어떤 값이 올지 모르기 때문에 검증이 필요함. null인지 아닌지 검증이 제일 우선
double calculator(double a, String operator, double b) { // 오류) This method must return a result of type double -> 반환한 것이 전부 if문 안에 있기 때문에 조건에 따라 반환을 하였지만 이프값이 걸리지 않으면 반환하지 못한다고 컴퓨터가 생각했기 때문에 if 밖에도 리턴 해야한다.
// 반환할 변수를 먼저 선언
//(비정상값) double변수result를 0으로 초기화
double result = 0;
if(operator == null) return result; // 비정상값을 반환하도록)
if(!operator.equals("+") && !operator.equals("-") && !operator.equals("*") && !operator.equals("/")) {
return result;
}
// 위에서 과정처리가 완료된 result값이기 때문에 정상적인 값이 나온다.
if(operator.equals("+")) result = a + b;
if(operator.equals("-")) result = a - b;
if(operator.equals("*")) result = a * b;
if(operator.equals("/")) result = a / b;
return result;
}
JVM 메모리 구조
기본형 매개변수와 참조형 매개변수 / 기본형 반환타입과 참조형 반환타입
기본형 매개변수 : 값이 복사되어 변수의 값을 읽기만 할 수 있다.
참조형 매개변수 : 인스턴스의 주소가 복사되어, 변수의 값을 읽고 변경할 수 있다.
기본형 반환타입 : 값 자체가 반환된다.
참조형 반환타입 : 힙 영역에 데이터를 저장하고 해당 힙 영역에 존재하는 객체의 주소를 반환한다.
class Human1 {
String name;
int age;
}
public class JVM {
static void function(int age, Human1 you) {
age = 30;
you.age = 30;
}
public static void main(String[] args) {
Human1 you = new Human1(); // 참조형 데이터 값은 바뀐다. 주소를 들고 가서 바꾸기 때문에.
you.name = "홍길동";
you.age = 20;
int age = 20; // 기본 데이터 값은 바뀌지 않는다.
function(age, you);
System.out.println(age);
System.out.println(you.age);
} // 블록이 끝나면 초기화. but 기본 데이터 값은 그대로.
}