화요일, 12월 24
Shadow

#012 QnA Class & Object

Question 2: The following code creates one Point object and one Rectangle object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection?


Point point = new Point(2,4);
Rectangle rectangle = new Rectangle(point, 20, 20);
point = null;

Answer 2: There is one reference to the Point object and one to the Rectangle object. Neither object is eligible for garbage collection.

Question 1: Consider the following class:
public class IdentifyMyParts {
public static int x = 7;
public int y = 3;
}

Question 1a. What are the class variables?
Answer 1a: x
Question 1b. What are the instance variables?
Answer 1b: y

Question 1c. What is the output from the following code:

IdentifyMyParts a = new IdentifyMyParts();
IdentifyMyParts b = new IdentifyMyParts();
a.y = 5;
b.y = 6;
a.x = 1;
b.x = 2;
System.out.println(“a.y = ” + a.y);
System.out.println(“b.y = ” + b.y);
System.out.println(“a.x = ” + a.x);
System.out.println(“b.x = ” + b.x);

Answer 1c: Here is the output:
a.y = 5
b.y = 6
a.x = 2
b.x = 2
A nested class is a member of its enclosing class and, as such, has access to other members of the enclosing class, even if they are declared private. As a member of OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)
——————————————————————————–
Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
——————————————————————————–

class OuterClass {

static class StaticNestedClass {

}
class InnerClass {

}
}

Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:
1.It is a way of logically grouping classes that are only used in one place.
2.It increases encapsulation.
3.Nested classes can lead to more readable and maintainable code.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {

class InnerClass {

}
}
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. The next figure illustrates this idea.

An InnerClass Exists Within an Instance of OuterClass
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

The StackOfInts class below is implemented as an array. When you add an integer (called “pushing”), it goes into the first available empty element. When you remove an integer (called “popping”), you remove the last integer in the array.

The StackOfInts class below (an application) consists of:

The StackOfInts outer class, which includes methods to push an integer onto the stack, pop an integer off the stack, and test to see if the stack is empty.
The StepThrough inner class, which is similar to a standard Java iterator. Iterators are used to step through a data structure and typically have methods to test for the last element, retrieve the current element, and move to the next element.
A main method that instantiates a StackOfInts array (stackOne) and fills it with integers (0, 2, 4, etc.), then instantiates a StepThrough object (iterator) and uses it to print out the contents of stackOne.
public class StackOfInts {

private int[] stack;
private int next = 0;  // index of last item in stack + 1

public StackOfInts(int size) {
//create an array large enough to hold the stack
stack = new int[size];
}

public void push(int on) {
if (next < stack.length)
stack[next++] = on;
}
public boolean isEmpty() {
return (next == 0);
}

public int pop(){
if (!isEmpty())
return stack[–next]; // top item on stack
else
return 0;
}

public int getStackSize() {
return next;
}

private class StepThrough {
// start stepping through at i=0
private int i = 0;

// increment index
public void increment() {
if ( i < stack.length)
i++;
}

// retrieve current element
public int current() {
return stack[i];
}

// last element on stack?
public boolean isLast(){
if (i == getStackSize() – 1)
return true;
else
return false;
}
}

public StepThrough stepThrough() {
return new StepThrough();
}

public static void main(String[] args) {

// instantiate outer class as “stackOne”
StackOfInts stackOne = new StackOfInts(15);

// populate stackOne
for (int j = 0 ; j < 15 ; j++) {
stackOne.push(2*j);
}

// instantiate inner class as “iterator”
StepThrough iterator = stackOne.stepThrough();

// print out stackOne[i], one per line
while(!iterator.isLast()) {
System.out.print(iterator.current() + ” “);
iterator.increment();
}
System.out.println();

}

}
The output is:
0 2 4 6 8 10 12 14 16 18 20 22 24 26

Note that the StepThrough class refers directly to the stack instance variable of StackOfInts.
Inner classes are used primarily to implement helper classes like the one shown in this example. If you plan on handling user-interface events, you’ll need to know about using inner classes because the event-handling mechanism makes extensive use of them.
Local and Anonymous Inner Classes
There are two additional types of inner classes. You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes. You will encounter such classes in advanced Java programming.
Modifiers
You can use the same modifiers for inner classes that you use for other members of the outer class. For example, you can use the access specifiers ? private, public, and protected ? to restrict access to inner classes, just as you do to other class members.

Types of Nested  Classes
Type    Scope         Inner
static nested   class member       no
inner [non-static]  class member       yes
local class   local        yes
anonymous class  only the point where it is defined yes

public class Problem {
String s;
static class Inner {
void testMethod() {
s = “Set from Inner”;
}
}
}
Question 1: The program Problem.java doesn’t compile. What do you need to do to make it compile? Why?
Answer 1: Delete static in front of the declaration of the Inner class. An static inner class does not have access to the instance fields of the outer class. See ProblemSolved.java.

Question 2: Use the Java API documentation for the Box class (in the javax.swing package) to help you answer the following questions.

a. What static nested class does Box define?
Answer 2a: Box.Filler

b. What inner class does Box define?
Answer 2b: Box.AccessibleBox

c. What is the superclass of Box’s inner class?
Answer 2c:[java.awt.]Container.AccessibleAWTContainer

d. Which of Box’s nested classes can you use from any class?
Answer 2d: Box.Filler

e. How do you create an instance of Box’s Filler class?
Answer 2e: new Box.Filler(minDimension, prefDimension, maxDimension)

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.