본문 바로가기
Java 배우기

Using Objects 객체 사용하기

by 노화방지 Anti-aging Hairstyle 2016. 1. 5.
반응형

객체 사용하기 Using Objects


일단 객체를 만들고 나면, 아마도 뭔가에 사용하고 싶습니다.
객체의 필드 중 하나의 값을 사용하거나, 그 필드 중 하나를 변경하거나, 동작을 수행하도록 그 메소드 중 하나를 호출할 필요가 있을 것입니다.

Once you've created an object, you probably want to use it for something. You may need to use the value of one of its fields, change one of its fields, or call one of its methods to perform an action.


객체의 필드 참조하기 Referencing an Object's Fields


객체 필드는 그 이름으로 접근합니다.
명확한 이름을 사용해야 합니다.

자기 클래스 내에서 필드에 대하여는 단순한 이름을 사용할 수 있습니다.
예를 들어, widthheightprint 하는 클래스 Rectangle 안에 명령문을 추가할 수 있습니다:
Object fields are accessed by their name. You must use a name that is unambiguous.

You may use a simple name for a field within its own class. For example, we can add a statement within the Rectangle class that prints the width and height:

System.out.println("Width and height are: " + width + ", " + height);


이 경우,  width와  height는 단순한 이름입니다.

In this case, width and height are simple names.

객체의 클래스 외부에 있는 코드는  dot (.) 운영자간단한 필드 이름이 뒤따르는, 객체 참조 또는 표현식(expression)을 사용해야 합니다:

Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:


objectReference.fieldName


예를 들어, 클래스 CreateObjectDemo 안의 코드는 클래스 Rectangle 코드의 외부에 있습니다.
따라서 RecrOne이라는 이름의 객체 Rectangle 내의 
originwidth, height  필드를 참조하려면, 클래스 CreateObjectDemo는 rectOne.origin, rectOne.width  rectOne.height 를 각각 사용해야 합니다.
프로그램은 rectOne
width와 height를 디스플레이 하기 위하여 이들 이름 2개를 사용합니다:
For example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. So to refer to the originwidth, and height fields within the Rectangle object named rectOne, the CreateObjectDemo class must use the names rectOne.origin,rectOne.width, and rectOne.height, respectively. The program uses two of these names to display the width and the height of rectOne:


System.out.println("Width of rectOne: "  + rectOne.width);
System.out.println("Height of rectOne: " + rectOne.height);


CreateObjectDemo 클래스의 코드에서 간단한 이름인 width와 height를 사용하려고하는 것은 이해가 되지 않습니다 - 이들 필드는 객체 내에만 존재 합니다.

나중에, 프로그램은 rectTwo에 대한 정보를 표시하기 위해 유사한 코드를 사용합니다.
동일한 유형의 객체가 동일한 인스턴스 필드의 자신의 복사본을 가지고 있습니다.
따라서, 각각의 객체 Rectangle은 
originwidth, height라는 필드를 갖고 있습니다. 

객체 참조를 통해 인스턴스 필드에 액세스 할 때 특정 객체의 필드 것을 참조.
CreateObjectDemo 프로그램의 두 객체 rectOne과 rectTwo는 서로 다른 필드 
originwidthheight를 갖고 있습니다.

필드에 액세스하려면 앞의 예에서와 같이 객체에 지정된 참조를 사용하거나 객체 참조를 반환하는 모든 표현을 사용할 수 있습니다.
new 연산자는 객체에 대한 참조를 반환 기억합니다.
그래서 새로운 객체의 필드에 액세스하는 새로운에서 반환 된 값을 사용할 수 있습니다:

Attempting to use the simple names width and height from the code in the CreateObjectDemo class doesn't make sense — those fields exist only within an object — and results in a compiler error.

Later, the program uses similar code to display information about rectTwo. Objects of the same type have their own copy of the same instance fields. Thus, each Rectangle object has fields named originwidth, and height. When you access an instance field through an object reference, you reference that particular object's field. The two objects rectOne and rectTwo in the CreateObjectDemo program have different originwidth, and height fields.

To access a field, you can use a named reference to an object, as in the previous examples, or you can use any expression that returns an object reference. Recall that the new operator returns a reference to an object. So you could use the value returned from new to access a new object's fields:

int height = new Rectangle().height;

This statement creates a new Rectangle object and immediately gets its height. In essence, the statement calculates the default height of a Rectangle. Note that after this statement has been executed, the program no longer has a reference to the created Rectangle, because the program never stored the reference anywhere. The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine.


객체의 메소드 호출하기 Calling an Object's Methods

You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.


objectReference.methodName(argumentList);


or:


objectReference.methodName();


The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:


System.out.println("Area of rectOne: " + rectOne.getArea());
...
rectTwo.move(40, 72);


The first statement invokes rectOne's getArea() method and displays the results. The second line moves rectTwo because the move() method assigns new values to the object's origin.x and origin.y.

As with instance fields, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. The new operator returns an object reference, so you can use the value returned from new to invoke a new object's methods:

new Rectangle(100, 50).getArea()

The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As shown, you can use the dot notation to invoke the new Rectangle's getArea() method to compute the area of the new rectangle.

Some methods, such as getArea(), return a value. For methods that return a value, you can use the method invocation in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle:

int areaOfRectangle = new Rectangle(100, 50).getArea();

Remember, invoking a method on a particular object is the same as sending a message to that object. In this case, the object that getArea() is invoked on is the rectangle returned by the constructor.


The Garbage Collector


Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null. Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.

The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.



반응형

댓글