본문 바로가기
자바(Java)/자바기초

[자바기초.013] 상속과 생성자

by 긱펀 2024. 3. 13.
반응형

[자바기초.013] 상속과 생성자

 

[1] 상속 관계에서 private 변수를 어떻게 다룰것인가?

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 {
   private int myX; // coordinates
   private int myY;
 
   public MPoint( ) {
      myX = 0;
      myY = 0;
   }
 
   public MPoint(int a, int b) {
      myX = a;
      myY = b;
   }
 
   // ... other methods not shown
 
}
 
public class NamedPoint extends MPoint {
   private String 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)
     {
        super(d1, d2);
        myName = name;
     }
cs

 

 

[유제2] 아래의 조건을 만족하는 클래스를 만들고 main에서 코딩을 완성하세요.

 

<조건>
  1. Make the class Square below inherit from Rectangle
  2. Add a Square constructor with 1 argument for a side that calls Rectangle‘s constructor with 2 arguments using super.
  3. Uncomment the objects in the main method to test drawing the squares.
  4. Add an area method to Rectangle that computes the area of the rectangle. Does it work for Squares too? Test it.
  5. 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
{
    private int length;
    private int width;
 
    public Rectangle(int l, int w)
    {
        length = l;
        width = w;
    }
 
    public void 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.
 
 
public class Main {
  public static void main(String[] args) {
    Rectangle r = new Rectangle(35);
    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
  }
}
 
 
 
cs

 

 

 

 

 

 


 

[유제 정답은 아래 "더보기" 클릭]

더보기

[유제1 정답]

1번과 3번

 

 

[유제2 정답]

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.*;
 
class Rectangle
{
    private int length;
    private int width;
 
    public Rectangle(int l, int w)
    {
        length = l;
        width = w;
    }
 
    public void 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.
  public int area() {
    return width * length;
  }
 
}
 
// 1. Make the class square inherit from Rectangle
class Square extends Rectangle
{
    // 2. Add a Square constructor with 1 argument for a side
    public Square(int l) {
      super(l, l);
    }
}
 
  // 5. Define the LongRectangle class here
  //    Do not make it public because only 1 class with main can be public in 1 file.
class LongRectangle extends Rectangle {
    public LongRectangle(int w) {
      super(2*w, w);
    }
}
 
 
public class Main {
  public static void main(String[] args) {
    Rectangle r = new Rectangle(35);
    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
    Square s2 = new Square(2);
    s2.draw();
 
    LongRectangle l1 = new LongRectangle(5);
    l1.draw();
 
    // print area
    System.out.println("area of Rectangle: " + r.area());
    System.out.println("area of Square: " + s.area());
    System.out.println("area of LongRectangle: " + l1.area());
 
  }
}
 
 
 
cs

 

 

 

 

 

 


 

728x90
반응형

댓글