클래스 01: 클래스, 클래스 객체 생성, constructor, instance fields, methods
* 클래스란?
* Class : the fundamental concept of object-oriented programming
* Classes are a blueprint for objects.Blueprints detail the general structure.
* Java programs have at least one class and one main() method.
Each class represents one real-world idea.
객체 지향 프로그래밍 언어에는 클래스 기반 언어와 프로토타입 기반 언어가 있다.
* 클래스 기반 언어
-> 클래스로 객체의 기본적인 형태와 기능을 정의하고, 생성자로 인스턴스를 만들어서 사용할 수 있다.
-> 클래스에 정의된 메서드로 여러 가지 기능을 수행할 수 있다.
-> 정확성, 안정성, 예측성 측면에서 우월
* 프로토타입 기반 언어
-> 객체의 자료 구조, 메서드 등을 동적으로 바꿀 수 있다.
->프로토타입은 자바스크립트로 객체 지향 구현을 하는데 필수 요소다
- 클래스는 멤버변수(속성), 메서드(기능), 생성자 등으로 구성된다.
클래스란 간단히 말하면 객체와 관련된 데이터와 처리 동작을 한데 모은 것.
설계도와 같다. 그 자체로는 이용할 수 없고 인스턴스를 만들어야 한다.
인스턴스는 메모리에 적재된 값이다.
실체화 작업 = 오브젝트 생성 = 인스턴스화
A class is the set of instructions that describe how an instance can behave and what information it contains.
클래스의 멤버 : 필드(Field, state, 멤버 변수), 메서드(Methods, behavior) -> dot(.)을 이용해 접근 및 호출 가능
- 클래스를 기술하는 것 = 클래스를 정의한다.
필드(=멤버변수) : 데이터
메서드 : 동작
클래스의 멤버 = 필드 + 메서드
eclipse에서 클래스 생성 : java 프로젝트 생성 - src - New - 클래스
class Npc {
// 필드 - 데이터
String name;
int hp;
void say() {
System.out.println("안녕하세요.");
}
}
public class MyNpc {
public static void main(String[] args) {
// 변수에는 인스턴스의 주소가 저장된다.
Npc saram1 = new Npc(); // 클래스를 객체로 생성 = 인스턴스화, 실체화
// 객체 접근하기 위해 .(dot)문법 사용
saram1.name = "경비";
saram1.hp = 100;
System.out.println(saram1.name + " : " + saram1.hp);
saram1.say();
}
}
- 클래스의 이름은 데이터 타입으로도 이용된다.
Variables that reference an instance have a type of the class name.
- 객체 생성, 레퍼런스
객체가 메모리에 생성되고 -> 객체의 메모리 주소를 "인스턴스 이름을 가진 변수"에 담아둔다
즉 변수에는 주소만 있을 뿐 객체는 다른 곳에 있다.
참조하고 있기 때문에 레퍼런스라고 한다.
ex. printing an instance of Store -> Store@6bc7c054
1st part Store: refers to the class
second part : refers to the instance's location in the computer's memory.
- 클래스의 인스턴스 얻는 법
1) public 생성자 : Constructor invocation
* Constructors : We create objects (instances of a class) using a constructor method.
The constructor is defined within the class.
shares a name with the class
We create instances by calling or invoking the constructor within main().
* Instance Fields(instance variables)
Instance fields are the state in our objects. -> a type of state each instance will possess
declare fields inside the class by specifying the type and name
public class Car {
String color;
pubilc Car() {
// instance fields available in scope of constructor method
}
public static void main(String[] args) {
//body of main method
}
}
* constructor method can have a parameter
parameter value assigned to the field
public class Car {
String color;
// constructor method with a parameter
public Car(String carColor) {
// parameter value assigned to the field
color = carColor;
}
public static void main(String[] args) {
// program tasks
Car ferrari = new Car("red");
}
}
The type of the value given to the invocation must match the type declared by the parameter.
* Methods
* method signature : public void startEngine()
it give the program some information about the method.
void : there is no specific output from the method.
- 만약 클래스를 정의할 때 생성자를 만들지 않더라도 default 생성자를 자동으로 만들어준다.
package lec11Pjt001;
public class Grandeur {
public String color;
public String gear;
public int price;
// 생성자 : 클래스 이름과 동일한 메서드
// 생성자를 통해 메모리에 객체가 올라간다.
public Grandeur() {
System.out.println("Grandeur constructor");
}
public void run() {
System.out.println("---run---");
}
public void stop() {
System.out.println("---stop---");
}
public void info() {
System.out.println("--- info() ---");
System.out.println("color : " + color);
System.out.println("gear : " + gear);
System.out.println("price : " + price);
}
}
package lec11Pjt001;
public class MainClass {
public static void main(String[] args) {
Grandeur myCar1 = new Grandeur();
myCar1.color= "red";
myCar1.gear = "auto";
myCar1.price = 30000000;
myCar1.run();
myCar1.stop();
myCar1.info();
Grandeur myCar2 = new Grandeur();
myCar2.color= "blue";
myCar2.gear = "manual";
myCar2.price = 25000000;
myCar2.run();
myCar2.stop();
myCar2.info();
}
}
또는 속성을 생성자에 바로 넣을 수 있도록 설계할 수 있다.
package lec11Pjt001;
public class Bicycle {
public String color;
public int price;
public Bicycle(String c, int p) {
System.out.println("Bicycle constructor");
color = c;
price = p;
}
public void info() {
System.out.println("-- info --");
System.out.println("color : " + color);
System.out.println("price : " + price);
}
}
속성을 주고 수정할 수도 있다.
package lec11Pjt001;
public class MainClass {
public static void main(String[] args) {
Bicycle myBicycle = new Bicycle("red", 100);
myBicycle.color = "yellow";
myBicycle.info();
}
}
- public으로 선언하지 않았다면?
같은 패키지 안에 있는 클래스에서만 인스턴스 만들 수 있어.
같은 패키지에 속한 클래스에서는 인스턴스 여러 개 만들 수 있다.
2) 정적 팩터리 메서드
[effective java] 생성자 대신 정적 팩터리 메서드를 고려하라.
정적 팩터리 메서드란? 클래스의 인스턴스를 반환하는 단순한 정적 메서드
- 정적 메서드(static method)
= 클래스 메서드
정적 메서드를 지칭할 때는 클래스 이름을 써야 한다.
ex.
public MyClass {
private MyClass(){}
public static MyClass getInstance() {
return new MyClass();
}
};
MyClass.getInstance()로 객체 인스턴스 만들 수 있어
출처 : codecademy