메소드 : 객체들 사이의 상호작용 수단
int result = add(10,20)
객체 간의 관계

public class(공개 클래스)로 선언할 수 있다. main() 메소드를 가지고 있는 실행 가능한 클래스new연산자는 객체 생성 후 연이어 생성자를 호출해서 객체를 초기화하는 역할을 한다.Animal cat = new Animal();

public class Car {
String model;
String color;
int maxSpeed;
Car(String model, String color, int maxSpeed) {
this.model = model;
this.color = color;
this.maxSpeed = maxSpeed;
}
}
public class CarExample {
public static void main(String[] args) {
Car myCar = new Car("model y", "white", 350);
// Car myCar2 = new Car(); // 기본 생성자 호출 못함
}
}
public class Car {
String company = "Tesla";
String model;
String color;
int maxSpeed;
Car(String model) {
this(model, "silver", 350);
}
Car(String model, String color) {
this(model, color, 350);
}
Car(String model, String color, int maxSpeed) {
this.model = model;
this.color = color;
this.maxSpeed = maxSpeed;
}
}
public class CarExample {
public static void main(String[] args) {
Car myCar = new Car("model x");
out(myCar);
Car myCar2 = new Car("model x", "red");
out(myCar2);
Car myCar3 = new Car("model y", "blue", 450);
out(myCar3);
}
private static void out(Car car) {
System.out.println(car.company);
System.out.println(car.model);
System.out.println(car.color);
System.out.println(car.maxSpeed);
System.out.println();
}
}
void run() { ... };
void setSpeed(int speed) { ... };
String getName() { ... };
public class Computer {
// 가변길이 매개변수를 갖는 메서드 선언
int sum(int ...values) {
int sum = 0;
for (int value : values) {
sum += value;
}
return sum;
}
}
public class ComputerExample {
public static void main(String[] args) {
Computer com = new Computer();
// 메서드 호출 시 배열 제공 1
int result = com.sum(new int[] {1,2,3});
System.out.println("1 : " + result);
// 메서드 호출 시 배열 제공 2
int[] nums = {1,2,3};
result = com.sum(nums);
System.out.println("2 : " + result);
// 메서드 호출 시 매개값 1, 2, 3 제공
result = com.sum(1,2,3);
System.out.println("3 : " + result);
}
}
return문 Unreachable code 컴파일 에러 발생
필드와 메소드는 선언 방법에 따라 인스턴스 멤버와 정적 멤버로 분류할 수 있다.
public class Car {
int gas;
void setSpeed(int speed) { ... }
}
gas필드와 setSpeed()메소드는 인스턴스 멤버이다. Car myCar = new Car();
myCar.gas = 10;
myCar.setSpeed(60);
Car yourCar = new Car();
yourCar.gas = 20;
yourCar.setSpeed(80);

gas필드는 객체마다 따로 존재하며, setSpeed()메소드는 각 객체마다 존재하지 않고 메소드 영역에 저장되고 공유된다. 자바는 클래스 로더를 이용해서 클래스를 메소드 영역에 저장하고 사용한다.

public class Calculate {
String color; // 계산기별로 색깔이 다를 수 있다.
static double pi = 3.14159; // 계산기에서 사용하는 파이 값은 동일하다.
setColor(String color) { this.color = color; } // 인스턴스 메소드
static int plus(int x, int y) { return x + y; } // 정적 메소드
}
public class Television {
static String company = "com";
static String model = "LCD";
static String info;
// 정적 블록
static {
info = company + "-" + model;
// Television.info는 "com-LCD"로 출력됨
}
}
static void Methid3() {
ClassName obj = new ClassName();
obj.field1 = 10;
dbj.methid1();
}
main()메소드도 정적 메소드이므로 동일한 규칙이 적용된다. final 필드는 초기값이 저장되면 이것이 최종적인 값이 되어서 프로그램 실행 도중에 수정할 수 없게 된다.
상수는 불변의 값을 저장하는 필드이다.
import문은 하위 패키지를 포함하지 않는다.com.hankook패키지도 사용해야하고 com.hankook.project패키지에 있는 클래스도 사용해야 한다면 두 개의 import문이 필요하다.| 접근제한자 | 제한 대상 | 제한 범위 |
|---|---|---|
| public | 클래스, 필드, 생성자, 메소드 | 없음 |
| protected | 필드, 생성자, 메소드 | 같은 패키지, 자식 객체만 사용 가능 |
| (default) | 클래스, 필드, 생성자, 메소드 | 같은 패키지 |
| private | 필드, 생성자, 메소드 | 객체 내부 |
public, default, private 접근 제한을 가질 수 있다.public class Car {
private int speed;
private boolean stop;
// getter
public int getSpeed() {
return speed;
}
public boolean isStop() {
return stop;
}
// setter
public void setSpeed(int speed) {
if (speed < 0 ) {
this.speed = 0;
return;
} else {
this.speed = speed;
}
}
public void setStop(boolean stop) {
this.stop = stop;
if (stop == true) this.speed = 0;
}
}
private 접근 제한해서 외부에서 new연산자로 생성자를 호출 못 하도록 막는 것public class Singleton {
// private 접근 권한을 갖는 정적 필드 선언과 초기화
private static Singleton singleton = new Singleton();
// private 접근 권한을 갖는 생성자 선언
private Singleton() {
}
// public(defalut 아닌가?) 접근 권한을 갖는 정적 메소드 선언
static Singleton getInstance() {
return singleton;
}
}
public class SingletonEx {
public static void main(String[] args) {
// 둘은 동일한 객체를 참조한다.
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
}
}