클래스 멤버 이해하기 Understanding Class Members
이 섹션에서는, 클래스의 인스턴스가 아닌, 클래스에 속한 필드와 메소드를 생성하기 위한 키워드 static
의 사용을 논의합니다.
In this section, we discuss the use of the static
keyword to create fields and methods that belong to the class, rather than to an instance of the class.
클래스 변수 Class Variables
많은 객체들이 동일한 클래스 청사진으로부터 생성될 때, 객체들 각각은 각자의 독특한 인스턴스 변수들의 카피를 갖게 됩니다.
클래스 Bicycle
의 경우, 인스턴스 변수들은 cadence
, gear
, speed
입니다.
각각의 Bicycle
객체는 서로 다른 메모리 장소에 저장되는, 이들 변수들에 대한 각자의 값들을 갖고 있습니다.
When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Bicycle
class, the instance variables are cadence
, gear
, and speed
. Each Bicycle
object has its own values for these variables, stored in different memory locations.
모든 객체들에게 공통인 변수들을 가져야 할 경우도 가끔씩 있습니다.static
modifier로 공통인 변수를 처리할 수 있습니다.
선언 안에 static
modifier가 포함된 필드들을 static fields 또는 class variables라고 합니다.static
modifier는 객체 보다는 클래스와 관계가 있습니다.
클래스의 모든 인스턴스는 클래스 변수를 공유하는데, 클래스 변수는 메모리 안에서 1개의 고정된 위치에 있습니다.
어떤 객체도 클래스 변수의 값을 변경할 수 있는데, 클래스의 인스턴스를 생성하지 않고도 클래스 변수를 조작할 수 있습니다.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static
modifier. Fields that have the static
modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
예를 들어, 많은 수의 객체 Bicycle
을 생성하고자 할 경우, 각각의 객체에게 첫째 객체부터 1로 시작되는 일련번호를 부여하십시오.
이 ID 번호는 각 객체에 대하여 유일하기 때문에 인스턴스 변수 입니다.
동시에, 얼마나 많은 Bicycle
객체가 생성되었는지 추적하기 위한 필드가 필요한데, 그래야 어떤 ID가 다음 객체에 부여되는지 알 수 있습니다.
그러한 필드는 개별 객체와는 관계가 없고 전체적으로 클래스와 관계가 있습니다.
이를 위해서 다음과 같은 클래스 변수 numberOfBicycles
가 있습니다:
For example, suppose you want to create a number of Bicycle
objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle
objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles
, as follows:
public class Bicycle { private int cadence; private int gear; private int speed; // 객체 ID에 대하여 인수턴스 변수를 추가 add an instance variable for the object ID private int id; // 인스턴스화된 Bicycle 객체 수에 대한 클래스 변수를 추가 add a class variable for the // number of Bicycle objects instantiated private static int numberOfBicycles = 0; ... }
클래스 변수는 아래 처럼 클래스 이름 그 자체로 참조합니다
Class variables are referenced by the class name itself, as in
Bicycle.numberOfBicycles
이렇게 하면 그들이 클래스 변수 임이 명확해집니다.
This makes it clear that they are class variables.
주: 아래 처럼 객체 참조를 갖고 static 필드를 참조할 수도 있지만,
Note: You can also refer to static fields with an object reference like
myBike.numberOfBicycles
but this is discouraged because it does not make it clear that they are class variables.
id 인스턴스 변수를 정하고, numberOfBicycles
클래스 변수를 증가시키기 위하여 Bicycle
생성자를 사용할 수 있습니다:
You can use the Bicycle
constructor to set the id
instance variable and increment the numberOfBicycles
class variable:
public class Bicycle { private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0; public Bicycle(int startCadence, int startSpeed, int startGear){ gear = startGear; cadence = startCadence; speed = startSpeed; // Bicycle의 수를 증가시키고 increment number of Bicycles // ID 번호를 할당 and assign ID number id = ++numberOfBicycles; } // ID인스턴스 변수를 리턴하기 위한 새로운 메소드 new method to return the ID instance variable public int getID() { return id; } ... }
클래스 메소드 Class Methods
자바 programming 언어는 static 변수는 물론 static methods도 지원합니다.
선언에 static
modifier가 포함된 static 메소드들은, 아래와 같이 클래스 인스턴스를 생성하지 않고 클래스 이름으로 invoke 할 수 있습니다.
The Java programming language supports static methods as well as static variables. Static methods, which have the static
modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args)
참고: 아래와 같이 객체 참조로 static메소드를 참조할 수 있습니다
Note: You can also refer to static methods with an object reference like
instanceName.methodName(args)
하지만 이것이 클래스 메소드라는 것이 명확하지 않기 때문에 권장되지 않습니다.
but this is discouraged because it does not make it clear that they are class methods.
public static int getNumberOfBicycles() {
예를 들어, numberOfBicycles
static field에 접근하기 위하여 Bicycle
class에 static 메소드를 추가할 수 있습니다:
A common use for static methods is to access static fields. For example, we could add a static method to the Bicycle
class to access the numberOfBicycles
static field:
public static int getNumberOfBicycles() { return numberOfBicycles; }
인스턴스와 클래스 변수 및 메소드의 조합은 허용되지 않습니다:
Not all combinations of instance and class variables and methods are allowed:
- 인스턴스 메소드는 인스턴스 변수와 인스턴스 메소드에 직접 접근할 수 있습니다.
Instance methods can access instance variables and instance methods directly. - 인스턴스 메소드는 클래스 변수와 클래스 메소드에 직접 접근할 수 있습니다.
Instance methods can access class variables and class methods directly. - 클래스 메소드는 클래스 변수와 클래스 메소드에 직접 접근할 수 있습니다.
Class methods can access class variables and class methods directly. - 클래스 메소드는 인스턴스 변수나 인스턴스 메소드에 직접 접근할 수 없습니다 - 클래스 메소드는 object reference를 사용해야 합니다.
또한, class methods는 키워드this
를 사용할 수 없는데 그 이유는this
가 참조할 인스턴스가 없기 때문입니다.
Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use thethis
keyword as there is no instance forthis
to refer to.
Constants
The static
modifier, in combination with the final
modifier, is also used to define constants. The final
modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI
, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).
Note: If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
The Bicycle
Class
After all the modifications made in this section, the Bicycle
class is now:
public class Bicycle { private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0; public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; id = ++numberOfBicycles; } public int getID() { return id; } public static int getNumberOfBicycles() { return numberOfBicycles; } public int getCadence() { return cadence; } public void setCadence(int newValue) { cadence = newValue; } public int getGear(){ return gear; } public void setGear(int newValue) { gear = newValue; } public int getSpeed() { return speed; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } }
'Java 배우기' 카테고리의 다른 글
Summary of Creating and Using Classes and Objects (0) | 2016.01.05 |
---|---|
Initializing Fields 필드 초기화 하기 (0) | 2016.01.05 |
Controlling Access to Members of a Class 클래스 멤버들에 대한 접근 제어 (0) | 2016.01.05 |
Using the this Keyword 키워드 this 사용하기 (0) | 2016.01.05 |
Returning a Value from a Method 메소드로부터 값을 리턴하기 (0) | 2016.01.05 |
댓글