티스토리에 저장했던 글을 옮겼습니다.
https://mrcocoball.tistory.com/66
https://mrcocoball.tistory.com/68
https://mrcocoball.tistory.com/75
리턴값 = 계산기객체.메소드(매개값1, 매개값2, ...);
int result = Calculator.add(10,20);
// 객체에 도트(.) 연산자를 붙이고 메소드 이름을 기술, 도트 연산자는 객체의 필드와 메소드에 접근 시 사용
// 매개값은 메소드를 실행하기 위해 필요한 데이터, 예를 들면 10 + 20 계산 필요 시 10, 20이 더하기 기능의 매개값
// 리턴값은 메소드가 실행되고 난 후 호출한 곳으로 돌려주는 값
public class 클래스 이름 {
}
public class Idol {
}
class Aqours {
}
new 클래스();
클래스 변수;
변수 = new 클래스();
Idol idol;
idol = new Idol();
// 혹은
클래스 변수 = new 클래스();
Idol idol = new Idol();
[클래스 선언 - Idol.java]
public class Idol {
}
[클래스로부터 객체 생성 - IdolExample.java]
public class IdolExample {
Idol i1 = new Idol();
Idol i2 = new Idol();
}
IdolExample을 실행하면 메모리에 클래스 변수와 객체가 생성됨.
Idol 클래스는 하나지만 new 연산자를 사용한 만큼 객체가 메모리에 생성됨
이러한 객체들이 바로 클래스의 인스턴스이며 같은 클래스로부터 생성되었으나
각 객체는 자신만의 고유 데이터를 가지며 메모리에서 활동하게 됨
클래스의 용도
public class Classname {
//필드
int fieldname;
// 생성자
Classname() { ... }
// 메소드
void mathodName()
자동차 객체 | 자동차 클래스 public class Car { |
---|---|
[고유 데이터] 제작회사 모델 색깔 최고 속도 | String company; String model; String color; int maxSpeed |
[상태 데이터] 현재 속도 엔진 회전수 | int speed; int rpm; |
[부품] 차체 엔진 타이어 | Body body; Engine engine; Tire tire; |
타입 필드 = 초기값 ;
String company = "현대자동차";
[Person 클래스]
void method() {
// Car 객체 생성
Car myCar = new Car();
// 필드 사용
myCar.speed=60;
}
// → Car 클래스를 통해 Car 객체를 생성한 뒤 myCar 변수가 Car를 참조
// 여기서 speed 초기값이 0인 상태인데 myCar.speed=60; 을 통해
// 생성자 내부의 speed와 메소드 내부의 speed 값이 60으로 변경됨
[Car 클래스]
// 필드
int speed;
// 생성자
Car() {
speed=0; // myCar.speed=60; 을 통해 60으로 변경
}
// 메소드
void method(...) {
speed=10; // myCar.speed=60; 을 통해 60으로 변경
}
[Car 클래스 필드 선언]
public class Car {
String company = "현대자동차";
String model = "그랜저";
String color = "검정";
int maxSpeed = 350;
int speed;
}
[외부 클래스에서 Car 필드값 읽기와 변경]
public class CarExample {
public static void main(String[] args) {
// 객체 생성
Car myCar = new Car();
// 필드값 읽기
System.out.println("제작회사 : " + myCar.company);
System.out.println("모델명 : " + myCar.model);
System.out.println("색깔 : " + myCar.color);
System.out.println("최고속도 : " + myCar.maxSpeed);
System.out.println("현재회사 : " + myCar.speed);
// 필드값 변경
myCar.speed = 60;
System.out.println("수정된 속도 : " + myCar.speed);
}
}
[public] 클래스() {}
클래스(매개 변수 선언, ...) {
// 객체의 초기화 코드
}
// Car 생성자 호출 시 3개의 매개값을 제공한다고 가정하면
// Car myCar = new Car("그랜저", "검정", 300);
// 일 때 생성자는 3개의 매개값을 받기 위해 매개 변수를 선언해야 함
public class Car {
// 생성자
Car(String model, String color, int maxSpeed) {...}
public class Korean {
// 필드
String nation = "대한민국"; // 초기값
String name;
String ssn;
// 생성자
public Korean(String n, String s) {
name = n; // 매개 변수 n으로 이름 지정
ssn = s; // 매개 변수 s로 번호 지정
}
}
// 지정 시
Korean k1 = new Korean("최쾅쾅", "990615-1123456")
Korean k2 = new Korean("최큥큥", "990616-1123564")
// 로 호출하면 필드의 name, ssn에 초기값 지정 가능
public class Korean {
// 필드
String nation = "대한민국"; // 초기값
String name;
String ssn;
// 생성자
public Korean(String name, String ssn) {
this.name = name; // 매개 변수 n으로 이름 지정
this.ssn = ssn; // 매개 변수 s로 번호 지정
}
}
// 으로 수정 가능
//※ Python의 self와 유사 self.name = name
// Car 클래스를 예시로 하면
public class Car {
Car() {...}
Car(String model) {...}
Car(String model, String color) {...}
Car(String model, String color, int maxSpeed) {...}
}
Car(String model, String color) {...}
Car(String color, String model) {...} // 오버로딩 아님
클래스 ( [매개 변수, ...] ) {
this (매개 변수, ..., 값, ...); // 클래스의 다른 생성자 호출
실행문;
}
Car(String model) {
this.model = model;
this.color = "은색";
this.maxSpeed = 250;
}
Car(String model, String color) {
this.model = model;
this.color = color;
this.maxSpeed = 250;
}
Car(String model, String color, int maxSpeed) {
this.model = model;
this.color = color;
this.maxSpeed = maxSpeed;
}
// -> 3개의 생성자 내용이 비슷하므로 앞의 2개의 생성자에서 this()를 사용, 마지막 생성자를 호출하도록 수정
Car(String model) {
this(model, "은색", 250); // 밑의 세번째 생성자로 호출됨
Car(String model, String color) {
this(model, color, 250); // 밑의 세번째 생성자로 호출됨
Car(String model, String color, int maxSpeed) {
this.model = model;
this.color = color;
this.maxSpeed = maxSpeed; // model~maxSpeed 해당 블록이 공통 실행 코드
}