기존에 사용하던 절차지향언어에 몇 가지 새로운 규칙을 추가한 것
코드의 재사용성을 높임
새로운 코드를 작성할 때, 기존의 코드를 이용하여 쉽게 작성할 수 있음
#include <stdio.h>
void swap_two(int *a, int *b){
int tmp = *b;
*b = *a;
*a = tmp;
}
void swap_three(int *a, int *b, int *c){
int tmp = *a;
*a = *b;
*b = *c;
*c = tmp;
}
int main(){
int a = 1;
int b = 2;
int c = 3;
swap_two(&a, &b);
printf("After swap_two: a = %d, b = %d\n", a, b); // 출력: a = 2, b = 1
swap_three(&a, &b, &c);
printf("After swap_three: a = %d, b = %d, c = %d\n", a, b, c); // 출력: a = 1, b = 3, c = 2
return 0;
}
class IntWrapper {
int value;
IntWrapper(int value) {
this.value = value;
}
}
public class Test {
static void swap(IntWrapper a, IntWrapper b){
int tmp = a.value;
a.value = b.value;
b.value = tmp;
}
static void swap(IntWrapper a, IntWrapper b, IntWrapper c){
int tmp = a.value;
a.value = b.value;
b.value = c.value;
c.value = tmp;
}
public static void main(String[] args) {
IntWrapper a = new IntWrapper(1);
IntWrapper b = new IntWrapper(2);
IntWrapper c = new IntWrapper(3);
System.out.println("Before swap:");
System.out.println("a=" + a.value + " b=" + b.value + " c=" + c.value);
swap(a, b);
System.out.println("\nAfter 2-way swap:");
System.out.println("a=" + a.value + " b=" + b.value);
swap(a, b, c);
System.out.println("\nAfter 3-way swap:");
System.out.println("a=" + a.value + " b=" + b.value + " c=" + c.value);
}
}
코드의 관리가 용이함
신뢰성이 높은 프로그래밍
제어자와 메서드를 이용해 데이터 보호
class : 객체를 정의해놓은 것
클래스로부터 객체를 만드는 과정 : 클래스의 인스턴스화
클래스로부터 만들어진 객체 : 클래스의 인스턴스
데이터 처리를 위한 데이터 저장형태의 발전과정
변수 → 배열 → 구조체 → 클래스
1개 → 같은 타입 여러개 → 다른 타입들 → 다른 타입들 + 함수
클래스 변수 : 클래스 영역 + 클래스가 메모리에 올라갈 때 생성
인스턴스 변수 : 클래스 영역 + 인스턴스가 생성되었을 때
지역 변수 : 클래스 영역 이외의 영역 + 변수 선언문이 수행되었을 때
method area, call stack, heap
메서드 앞에 static → 클래스 메서드
없으면 → 인스턴스 메서드
인스턴스와 관계없는 메서드 → 인스턴스 변수를 사용하지 않으면 일반적으로 클래스 메서드로 정의
인스턴스 변수를 사용하지 않는데 클래스 메서드로 정의하지 않으면, 메서드 호출 시 메서드를 찾는 과정이 추가되기 때문
한 클래스 내에 같은 이름의 메서드를 여러 개 정의하는 것
가변인자 (variabler arguments)
타입… 변수명
public PrintStream printf (String... str) { ... }
public PrintStream printf (String formant, Object... args) { ... }
public concatenate (String... str) { ... }
public concatenate (String[] str) { ... }
String result = concatenate (new String[0]);
String result = concatenate (null);
String result = concawtenate (); // 에러 인자가 필요함
배열로 지정하게되면, 반드시 인자를 지정해야함 → 인자를 생략할 수 없음
연산자 new가 인스턴스를 생성하는 것이고, 생성자는 인스턴스를 생성하는 것이 아니다.
단순히 인스턴스 변수들의 초기화에 사용되는 조금 특별한 메서드이다.
생성자 간에도 서로 호출이 가능
간격하고, 직관적인 코드를 작성할 수 있음
ex) 인스턴스 복사본을 만들때
class Car {
String color;
String gearType;
int door;
Car() {
this("white","auto",4);
}
Car(Car c) {
this(c.color, c.gearType, int door);
}
Car(String color, String gearType, int door){
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
명시적 초기화, 클래스 초기화 블록, 인스턴스 초기화 블록