신용권님의 ''이것이 자바다'' 공부 기록
책을 보면서 내용을 정리했습니다. 이것이 자바다 커뮤니티 : https://cafe.naver.com/thisisjava
객체 생성 역할로 new 클래스(); 으로 생성할 수 있다. 클래스()은 생성자를 호출하는 코드로 생성된 객체는 힙 메모리 영역에 생성된다.
new 연산자는 객체를 생성 후, 객체 생성 번지를 리턴한다.
new 연산자에 의해 리턴 된 객체의 번지를 저장한다. (참조 타입 변수)
힙 영역의 객체를 사용하기 위해 사용한다.
클래스 변수;
변수 = new 클래스();
클래스 변수 = new 클래스();
public class ClassName {
//필드
int fieldName;
//생성자
ClassName() {...}
//메서드
void methodName() {...}
}
타입 필드 [ = 초기값];
String company = "현대자동차";
String model = "그랜저";
int maxSpeed = 300;
int productionYear;
int currentSpeed;
boolean engineStart;
void method() {
//Car 객체 생성
Car myCar = new Car();
//필드 사용
myCar.speed = 60;
}
//필드
int speed;
//생성자
Car() {
speed = 0;
}
//메서드
void method(...) {
speed = 10;
}
Car 클래스
Person 클래스는 외부객체이므로 "변수.필드이름"식으로 접근해야한다.
소스 파일(Car.java)
public class Car {...}
바이트 코드 파일(Car.class)
public class Car {
public Car() {} //기본 생성자 자동 추가
}
소스 파일(CarTest.java)
Car myCar = new Car(); // <-- 기본 생성자
클래스(매개변수선언, ...) {
//객체의 초기화 코드
}
public class Car {
//생성자
Car(String model, String color, int maxSpeed) {...}
}
-------------------------------------------------------
Car myCar = new Car("그랜저", "검정", 300);
//생성자의 매개값으로 초기값 설정
Korean k1 = new Korean("임자바", "900111-1234567");
Korean k2 = new Korean("배자바", "900222-2345678");
package com.kosta.day04;
public class StudentTest {
public static void main(String[] args) {
method1();
}
private static void method1() {
Student lim = new Student();
lim.printStudent();
Student bae = new Student("배대장", "정보보호", "18014016", 23);
bae.printStudent();
Student kim = new Student("김갑수", "영문과");
kim.printStudent();
Student park = new Student("박을용", 27);
park.printStudent();
}
}
package com.kosta.day04;
//class (object들의 공통된 특성, 행동)
public class Student {
// 1.멤버변수 선언 (필드)
String name;
String major;
String no;
int age;
// 2.생성자 메서드 선언 (생성시 자동호출 : 초기화 목적)
// 정의하지않는다면 Default 생성자 제공
// 정의한다면 Default 생성자 없어짐 (사용불가)
public Student() {
//default 생성자 : argument없음
System.out.println("Default 생성자 생성: No argument");
}
public Student(String name, int age) {
//생성자가 다른모양의 생성자를 호출
this(name, null, null, age);
}
public Student(String name, String major) {
//생성자가 다른모양의 생성자를 호출
this(name, major, null, 20);
}
public Student(String name, String major, String no, int age) { //오버로딩
System.out.println("=======================학생 생성");
this.name = name;
this.major = major;
this.no = no;
this.age = age;
}
// 3.메서드(기능,행동)
void study() {
System.out.println(name + "공부 중");
}
String getMajor() {
return name + "의 전공은 " + major;
}
int getAge() {
return age;
}
void printStudent() {
System.out.println("이름: " + name);
System.out.println("전공: " + major);
System.out.println("학번: " + no);
System.out.println("나이: " + age);
}
}
메소드 선언
void powerOn() {...}
double divide(int x, int y) {...}
메소드 호출
powerOn();
double result = divide(10, 20);
메소드 선언
void powerOn() {...}
double divide(int x, int y) {...}
메소드 호출
powerOn();
#1
double result = divide(10, 20);
#2
byte b1 = 10;
byte b2 = 20;
double result = devide(b1, b2);
int plus(int x, int y) {
int result = x + y;
return result;
}
boolean isLeftGas() {
if(gas == 0) {
System.out.println("gas가 없습니다.");
return false;
}
System.out.println("gas가 있습니다.");
return true;
}
외부호출
void 외부메소드() {
Car car = new Car();
car.run();
car.stop();
car.sound();
}
내부호출
메소드 선언
void run() {...}
void stop() {...}
void sound() {...}
void 내부메소드() {
run();
stop();
sound();
}
class 클래스 {
리턴타입 메소드이름 (타입 변수, ...) {...}
(무관) (동일) (매개변수의 타입, 개수, 순서가 달라야한다.)
리턴타입 메소드이름 (타입 변수, ...) {...}
ex)
//plus(10, 20)
int plus(int x, int y) {
int result = x + y;
return result;
}
//plus(10.5, 20.3)
double plus(double x, double y) {
double result = x + y;
return result;
}
public class Car {
//필드
int gas;
//메소드
void setSpeed(int speed) {...}
}
Car myCar = new Car();
myCar.gas = 10;
myCar.setSpeed(60);
Car yourCar = new Car();
yourCar.gas = 20;
yourCar.setSpeed(80);
객체(인스턴스) 자신의 참조(번지)를 가지고 있는 키워드
객체 내부에서 인스턴스 멤버임을 명확히 하기 위해 this. 사용
매개변수와 필드명이 동일할 때 인스턴스 필드임을 명확히 하기 위해 사용
Car(String model) {
this.model = model;
}
void setModel(String model) {
this.model = model;
}
public class 클래스 {
//정적 필드
static 타입 필드 [= 초기값];
//정적 메소드
static 리턴타입 메소드(매개변수선언, ...) {...}
}
클래스.필드;
클래스.메소드(매개값, ...);
public class Calculator {
static double pi = 3.141592;
static int plus(int x, int y) {...}
static int minus(int x, int y) {...}
}
바람직한 사용
double result1 = 10 * 10 * Calculator.pi;
int result2 = Calculator.plus(10, 5);
int result3 = Calculator.minus(10, 5);
바람직하지 못한 사용
Calculator myCalcu = new Calculator();
double result1 = 10 * 10 * myCalcu.pi;
int result2 = myCalcu.plus(10, 5);
int result3 = myCalcu.minus(10,5);
public class Calculator {
String color; //계산기 별로 색이 다를 수 있음
static double pi = 3.141592; //계산기에서 사용하는 파이값은 동일
}
public Calculator {
String color;
void setColor(String color) {this.color = color;}
static int plus(int x, int y) {return x + y;}
static int minus(int x, int y) {return x = y;}
}
public class Television {
static String company = "Samsung";
static String model = "LCD";
static String info;
static {
info = company + "-" + model;
}
}
//인스턴스 필드와 메소드
int field1;
void method1() {...}
//정적 필드와 메소드
static int field2;
static void method2() {...}
//정적 블록
static {
field1 = 10; // x 컴파일에러
method1(); // x 컴파일에러
field2 = 10; // o
method2(); // o
}
//정적 메소드
static void Method3 {
this.field1 = 10; // x 컴파일에러
this.method1(); // x 컴파일에러
field2 = 10; // o
method2() // o
}
static void Method3() {
ClassName obj = new ClassName();
obj.field1 = 10;
obj.method1();
}
클래스 변수 1 = 클래스.getInstance();
클래스 변수 2 = 클래스.getInstance();
/*
Singleton obj1 = new Singleton(); //컴파일 에러
Singleton obj2 = new Singleton(); //컴파일 에러
*/
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
if(obj1 == obj2) {
System.out.println("같은 Singleton 객체입니다.");
} else {
System.out.println("다른 Singleton 객체입니다.");
}
package com.mycompany;
public class Car {
com.hankook.Tire tire = new.com.hankook.Tire();
}
package com.mycompany;
import com.hankook.Tire;
[or import com.hankook.*;]
public class Car {
Tire tire = new Tire();
}
클래스 선언할 때 필드는 일반적으로 private 접근 제한
package com.kosta.day04;
public class Person {
private static int numberOfPersons;
int age;
String name;
Person() {
this(12, "Anonymous");
}
Person(int age, String name) {
this.age = age;
this.name = name;
numberOfPersons++;
}
void selfIntroduce() {
System.out.println("내 이름은 " + name + "이며, 나이는 " + age + "살 입니다.");
}
static int getPopulation() {
return numberOfPersons;
}
public static void main(String[] args) {
Person anonymous = new Person();
anonymous.selfIntroduce();
Person lim = new Person(25, "임덕배");
lim.selfIntroduce();
System.out.println(Person.getPopulation() + "명의 인구수가 있습니다.");
}
}