subclass는 자신이 확장하는 superclass에서 public method를 상속하지만 superclass의 private instance variable에 직접 액세스할 수는 없습니다. 그리고 subclass는 superclass의 생성자(constructor)를 상속하지 않습니다. 하지만 상속된 인스턴스 변수는 적절하게 초기화되어야 합니다. 그렇지 않으면 상속된 메서드(method) 중 어느 것도 제대로 작동하지 않을 것입니다. 그렇다면 subclass가 superclass의 private variable을 어떻게 초기화할 수 있을까요?
[예제1] 아래의 상속 관계를 가지는 코드를 보고 생성자 부분의 설명을 읽어보자.
subclass는 superclass의 public method를 상속 받지만, superclass의 private instance variable(private object field)에 직접 접근할 수는 없습니다. 그리고 subclass는 superclass의 생성자(constructor)를 상속받지 않습니다. 하지만 상속된 instance variable은 적절하게 초기화되어야 합니다. 그렇지 않으면 상속된 method 중 어느 것도 제대로 작동하지 않을 것입니다. 그렇다면 subclass가 superclass의 private variable을 어떻게 초기화할 수 있을까요?
private variable을 초기화 하는 첫번째 방법으로 superclass에 들어있는변수에 대한 public setter method를 제공하는 경우 subclass는 이 setter method를 사용하여 ,변수에 접근할 수 있습니다.
두번째 방법으로 super 생성자를 실행할 때 변수들을 초기화 할 수 있습니다.
subclass의 객체(object)를 생성하면 superclass의 객체(object)가 먼저 생성되고 자식 객체가 그 후에 생성된다.
superclass의 기본생성자(default constructor)는 subclass 생성자의 맨 첫 줄에서 super() 형태로 자동 호출된다.
superclass에 매개변수가 있는 생성자만 있다면 subclass 생성자에서 반드시 superclass 생성자 호출을 위한 super(매개값)을 작성해야 한다.
superclass 생성자는 subclass가 직접 액세스할 수 없는 전용 변수(private field)를 포함하여 superclass에 선언된 인스턴스 변수를 초기화할 수 있습니다.
[참고] 접근제한자 : 접근에 제한을 주는 것 -public: 어디서나 접근, 참조 가능 -protected => 상속일 경우 : 상속된 곳에서만 / 상속이 아닐 경우 : 같은 패키지 내에서만 -default : 같은 패키지 내에서만 -private : 같은 클래스 내에서만
[유제1] 아래 MPoint 및 NamedPoint의 클래스 정의가 주어졌을 때, 다음 생성자(I, II 및 III로 표시됨) 중 NamedPoint 클래스에서 오류없이 실행되는 것은 무엇입니까?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class MPoint {
privateint myX; // coordinates
privateint myY;
public MPoint( ) {
myX =0;
myY =0;
}
public MPoint(int a, int b) {
myX = a;
myY = b;
}
// ... other methods not shown
}
publicclass NamedPoint extends MPoint {
privateString myName;
// constructors go here
// ... other methods not shown
}
// Proposed constructors for this class:
I. public NamedPoint()
{
myName ="";
}
II. public NamedPoint(int d1, int d2, String name)
{
myX = d1;
myY = d2;
myName = name;
}
III. public NamedPoint(int d1, int d2, String name)
Add aSquareconstructor with 1 argument for a side that callsRectangle‘s constructor with 2 arguments using super.
Uncomment the objects in themainmethod to test drawing the squares.
Add an area method toRectanglethat computes the area of the rectangle. Does it work forSquarestoo? Test it.
Add another subclass called LongRectangle which inherits from Rectangle but has the additional condition that the length is always 2 x the width. Write constructors for it and test it out. Do not make it public (because only 1 class per file can be public).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.*;
class Rectangle
{
privateintlength;
privateint width;
public Rectangle(int l, int w)
{
length= l;
width = w;
}
publicvoid draw()
{
for (int i =0; i <length; i++)
{
for (int j =0; j < width; j++)
{
System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
// 4a. Add an area method to compute the area of the rectangle.
}
// 1. Make the class square inherit from Rectangle
class Square
{
// 2. Add a Square constructor with 1 argument for a side
}
// 5. Define the LongRectangle class here
// Do not make it public because only 1 class with main can be public in 1 file.
publicclass Main {
publicstaticvoid main(String[] args) {
Rectangle r =new Rectangle(3, 5);
r.draw();
// 3. Uncomment these to test
// Square s1 = new Square(1);
// s1.draw();
// Square s = new Square(3);
// s.draw();
// 4b. Add some tests for your area method after you write it
댓글