Submit your assignment using the following file format:

    LabNumber_StudentName_Student_ID.zip
    Example: Lab5_Hongkildong_201620505.zip

   

The zip file will contain two types of files, namely:

  1) report file with file format Report_Lab number (eg. report_5) to answer theory questions and to write the screen shot that display the output of your program

  2) Source code file that contains classes to answer programming questions.


Objectives

1. Learning the concept of an implicit parameter called this reference keyword
2. Learning the concept of 
Overloaded constructor using this reference keyword.
3. Learning and utilizing the concept of 
composition (HAS-A relationship between two classes).

4. Learning and utilizing the use of final member variable

 

1. "this" 참조 키워드라는 implicit parameter의 개념 학습
2. "this" 참조 키워드를 사용하여 Overloaded constructor의 개념을 익힌다.
3. composition의 개념(두 계급의 HAS-A 관계)을 배우고 활용한다.
4. "final" 변수의 학습 및 활용


Questions

1. Answer the questions about Account class in Fig 3.8 and AccountTest class in Fig 3.9.

A. Add the following constructor in the Account class. This constructor should call an original constructor of the Account class (2 point).

   Account 클래스에 다음 생성자를 추가하십시오. 이 생성자는 Account 클래스의 원래 생성자를 호출해야 한다.

public Account (String name); // initializing name by the given String and balance by zero. 
{
.............
}

B. Using the code in (A), edit 10th line of AccountTest class as shown below, and then execute the program and include screen shot (3 point)

 

 

   (A)의 코드를 사용하여 101번째 줄 AccountTest 클래스를 아래 그림과 같이 바꾼 후, 프로그램을 실행하고 스크린샷 포함

Account account2 = new Account("Hong Kil-Dong");

 


2. Answer the following questions about ThisTest class and SimpleTime class in Fig.8.4. Note that one source file contains both test class and normal classes.

A. “this.toUniversalString() at line 34 and toUniversalString()at line 35 within buildString() method have the same results. Why they have the same result? Explain only the reason. (3 point)

 

Answer : this 키워드는 이 클래스를 기반으로 생성된 인스턴스를 가리키는 reference이다.

"toUniversalString" method를 호출하면 SimpleTime class를 기반으로 하는 인스턴스의 hour, minute, second가 호출된다.

"this"를 추가한 "toUniversalString()" method를 호출하면 SimpleTime class를 기반으로 만들어진 인스턴스의 메서드가 호출되고, 이 인스턴스는 위의 인스턴스와 동일한 인스턴스이므로 동일한 결과를 갖는다. 

 

Answer : "this" keyword is a reference to an instance created based on this class.
Invoking the "toUniversalString" method calls the hour, minute, second of the instance based on the "SimpleTime" class.
Invoking the "toUniversalString()" method with "this" added invokes the method of the instance created on the basis of the "SimpleTime" class, which is the same instance as the above

So they have the same result.

 

   34번째 줄의 "this.toUniversalString()"은

   buildString() 안의 35번째 줄의 "toUniversalString()"과 동일한 결과를 갖는다.

   왜 그들은 같은 결과를 갖는가? 이유만 설명하라.

 

B. From line 25 to line 27, remove this reference variables in SimpleTime() constructor . Re- implement Simple Time() constructor to get the same result as shown in (A) and include the screen shot (3 point)

 

 

   25행부터 27행까지, SimpleTime() 생성자에서 "this" 참조 변수를 제거해라.

   (A)와 같은 결과가 나오게 SimpleTime() 생성자를 다시 구현하고 스크린샷을 올려라.

 

생성자에 대한 설명 : https://woochan-autobiography.tistory.com/85

 

java - 생성자(constructor)

회사에 출근해서 업무를 시작하기 전에 제일 먼저 하는 일이 아마 책상 정리일 것이다. 커피를 내리는 경우도 있을 것이고, 컴퓨터 부팅을 시작하기도 할 것이다. 즉 어떤 일을 시작하기 전에 준비를 하게 되는데..

woochan-autobiography.tistory.com

 


 

3. Answer the questions using Date, Employee, EmployeeTest classes in Fig 8.7 /8.8 / 8.9

A. Between line 10 and line 11, in the EmployeeTest (Fig.8.9), when you add the lines of code in the following box , what happens ? Explain your reason. (3 points

 

Answer : 에러가 난다. "Employee" constructor 에 필요로 하는 매개변수가 없기 때문에 "e1"이라는 인스턴스를 만들지 못하기 때문이다.

 

Answer : There is an error because the "Employee" constructor cannot create an instance called "e1" because it does not have the required parameters.

 

  10줄과 11줄 사이, EmployeeTest(그림 8.9)에서, 밑의 코드를 추가하면 어떻게 되는가? 이유를 설명하십시오.

Employee e1 = new employee(); 
System.out.println(e1);

 

B. Add final keyword at line 8 and line 9 in the employee class (fig 8.8) and execute the program. Is the output of the program the same before and after adding the final key word? Explain your reason. (3 point)

 

Answer : Output of the program is same. Because 

"final" keword는 실행되는 과정에서 한번 값이 정해진 이후에는 변수의 값이 바뀌지 않도록 하는 규제다. 

"birthDate" 변수와 "hireDate" 변수의 값을 특정 값으로 지정하지 않았기 때문에 결과에 영향을 주지 않는다.

 

Answer : The output of the program is same. 
The "final" keyword is a regulation that prevents the value of a variable from changing once the value is set in the process of execution.
Because the value of the "birthDate" variable and the "HireDate" variable is not specified as a specific value, the result is not affected.

 

  8행과 9행의 "final" 키워드를 "employee class"(그림 8.8)에 추가하고 프로그램을 실행한다.

  "final" 키워드를 추가하기 전과 후의 프로그램 출력이 동일한가? 당신의 이유를 설명하시오.

 

C. In the Employee class (Fig.8.8), when you add the lines of code in the following box, what happens? Explain your reason (3pts)

 

Answer : 에러가 난다. 

final은 실행되는 과정에서 한번 값이 정해진 이후에는 변수 내의 값이 바뀌지 않도록 하는 규제다. 

Fig8.8에서 birthDate 변수에 final 키워드를 추가함으로써 값이 고정되었기 때문에 setBirthDate method를 사용할 수 없다.

Same as hireDate variable.

"final" 키워드를 추가하지 않는다면 정상적으로 작동한다.

 

Answer : There's an error. 
The "final" keyword is a regulation that prevents the value of a variable from changing once the value is set in the process of execution. 
In Fig8.8, the "setBirthDate" method is not available because the value is fixed by adding the "final" keyword to the "birthDate" variable.
Same as "hardDate" variable.
If you don't add the "final" keyword, it works normally.

 

if add "final" keyword

if not add "final" keyword

 

 Employee 클래스(그림 8.8)에서 밑의 코드를 추가하면 어떻게 되는가? 이유를 설명하라

  •   Add final modifier at line 8 and line 9.

  •   Between line 21 and line 22, Add the source code of SetBirthDate() and

      SetHireDate() methods

  •   Between line 12 and 13, do the following

  •   Date b = new Date(7,7,1977);
  •   Date h = new Date(8,8,1988);
  •   Employee e2 = new Employee( kim, lee, b ,h);  
  •   System.out.println(e2);

 


this()

- this method는 생성자 안에서만 사용이 가능하다.

- 생성자에서 생성자 호출, 생성자가 가지고 있는 parameter를 비교해서 맞는 생성자를 찾아서 해당 변수를 전달한다.

- 생성자의 갯수가 많을수록 this method를 많이 사용한다.

 

1. 클래스 메서드

- 메서드 앞에 static 이 붙어 있으면 클래스 메서드

- 클래스 메서드도 클래스 변수처럼 객체를 생성하지 않고 '클래스이름.메서드이름(매개변수)'와 같이 호출가능

 

2. 인스턴스 메서드

- 반드시 객체 생성해야만 호출 가능

 

그렇다면, 어느 경우에 static을 사용해 클래스 메서드로 정의할 것인가?

 

클래스는 '데이터(변수)와 데이터에 관련된 메서드의 집합'이므로 클래스내에 있는 메서드와 멤버변수는 아주 밀접한 관계.

인스턴스메서드는 인스턴스 변수와 관련된 작업을 하는, 즉 메서드의 작업을 수행하는데 인스턴스를 필요로 하는 메서드이다.

 

반면 메서드중에서 인스턴와 관계 없는(인스턴스 변수나 인스턴스 메서드를 사용하지 않는)메서드를 클래스 메서드(static 메서드)라 정의한다.

 

즉,

- 클래스를 설계할 때, 멤버변수 중 모든 인스턴스에 공통적으로 사용해야하는 것에 static을 붙인다.

- 클래스변수(static 변수)는 인스턴스를 생성하지 않아도 사용할 수 있다.

- 클래스 메서드(static 메서드)는 인스턴스 변수를 사용할 수 없다.

: static이 붙은 메서드는 인스턴스 생성 없이 호출 가능한 반면, 인스턴스 변수는 인스턴스를 생성해야만 만들어지 때문에 static이 붙은 메서드에서 인스턴수 변수의 사용을 허용하지 않음. 그러나, 인스턴스 변수나 인스턴스 메서드에서는 static이 붙은 멤버들을 사용한 것은 언제나 가능.

- 메서드 내에서 인스턴수 변수를 사용하지 않는 반면, static을 붙이는 것을 고려한다

: 메서드의 작업내용 중에 인스턴스 변수를 필요로 한다면, static을 붙일 수 없다.

반대로 인스턴스 변수를 필요로 하지않는다면 static을 붙이자. (메서드 호출시간 짧아지기 때문에 효율 증가)

- 클래스의 멤버변수 중 모든 인스턴스에 공통된 값을 유지해야하는 것이 있는지 살펴보고 있으면 static을 붙인다.

 


명시적으로 필드를 초기화할 수 있다.

 

this 키워드를 사용하면 imlpicit하게 = 암묵적으로 변수를 지정할 수 있다.

this 키워드는 한 생성자에서 다른 생성자로 호출할 수 있게 한다.

 

초기화하는 두가지 방법이 있다.

  1. 생성자 안에 세팅하기
  2. 선언을 통해 할당하기

 

초기화하는 블록은 세번째 메커니즘이다.

클래스 선언은 코드의 임의적인 블록을 포함한다.

이 블록은 클래스의 객체가 만들어질 때 실행된다.

초기화 블록이 먼저 돌고, 그 다음 생성자의 본체가 수행된다.

 

 

'📌 java > Object-oriented Programming' 카테고리의 다른 글

java - 상속의 참조 관계  (0) 2020.04.26
Homework_W6  (0) 2020.04.23
Homework_W4  (0) 2020.04.07
Homework_W3  (0) 2020.03.31
java - accesor, mutator  (0) 2020.03.31
복사했습니다!