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

[자바기초.017] super 키워드

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

[자바기초.017] super 키워드

 

[1] super 키워드

  • subclass는 superclass로부터 상속받은 필드와 메소드를 사용할 수 있습니다.
  • 그런데 subclass가 superclass의 메소드를 재정의 해서 사용하는 "오버라이드(override)"를 했다고 가정했을 때,
  • 만약 superclass의 override된 메소드를 사용하고 싶다면 어떻게 해야 할까요?
  • 이럴 때 바로 super.method()로 superclass의 메소드를 실행할 수 있습니다.

 

[2] super의 2가지 쓰임새

  1. super() / super(arguments): superclass의 생성자(constructor)를 subclass의 생성자 첫 줄에서 실행할 때 사용.
  2. super.method() : superclass의 메소드(method)를 사용할 때(not constructors)   .
The keyword super is very useful in allowing us to first execute the superclass method and then add on to it in the subclass.

 

 

[예제1] 아래 예제 코드를 보고 super.method()의 쓰임새를 살펴 봅시다.

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
class Person {
    private String name = null;
    public Person(String theName) {
        name = theName;
    }
 
    public String getFood() {
        return "Hamburger";
    }
}
 
class Student extends Person {
    private int id;
    private static int nextId = 0;
    public Student(String theName) {
        super(theName);
        id = nextId;
        nextId++;
    }
 
    public String getFood() {
        String output = super.getFood();
        return output + " and Pizza";
    }
 
    public int getId() {
        return this.id;
    }
 
    public void setId(int theId) {
        this.id = theId;
    }
}
 
 
public class Main {
  public static void main(String[] args) {
    Student p = new Student("Javier");
    System.out.println(p.getFood());
  }
}
cs

 

 

  • Student 클래스는 Person 클래스의 상속을 받는다.
  • Student 클래스의 getFood() 메소드는 superclass의 메소드를 오버라이드 한 것이다.
  • 그래서 subclass에서 superclass의 getFodd() 메소드를 사용하기 위해 super.getFood() 메소드를 사용했다.

 

 

[유제1] 아래의 영어로 된 조건문을 읽어보고 아래 코드에 추가로 코딩해 보세요.

<조건>
1.Add another subclass called Vegan that inherits from the Student class.
2.Add a Vegan contructor that takes a name as an argument and passes it to the super constructor.
3.Override the getFood() method in Vegan to call the superclass getFood() but add a “No “ in front of it and then say “but “ and add a vegan food.
4.Change Javier to a Vegan object in main() and try it out!

 

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
class Person {
    private String name = null;
    public Person(String theName) {
        name = theName;
    }
 
    public String getFood() {
        return "Hamburger";
    }
}
 
class Student extends Person {
    private int id;
    private static int nextId = 0;
    public Student(String theName) {
        super(theName);
        id = nextId;
        nextId++;
    }
 
    public String getFood() {
        String output = super.getFood();
        return output + " and Pizza";
    }
 
    public int getId() {
        return this.id;
    }
 
    public void setId(int theId) {
        this.id = theId;
    }
}
 
 
public class Main {
  public static void main(String[] args) {
    Student p = new Student("Javier");
    System.out.println(p.getFood());
  }
}
cs

 

 


 

[예제2] 아래 코드를 보며, subclass와 superclass 간의 메소드 실행 순서에 대해 알아보자.

 

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
class Parent
{
    public void work()
    {
        System.out.println("I have to clean my kitchen.");
        rest(); // 이 부분이 중요! (subclass? superclass?)
    }
 
    public void rest()
    {
        System.out.println("I rest in the living room.");
    }
}
 
class Child extends Parent
{
  @Override
    public void work()
    {
      System.out.println("I have to do my homework.");
      super.work();
    }
  @Override
    public void rest()
    {
      System.out.println("I rest in my room.");
      super.rest();
    }
}
public class Main {
  public static void main(String[] args) {
    Parent ch = new Child();
    ch.work();
  }
}
cs

 

[실행결과]

 

  • 위 코드에서 Parent ch = new Child() 부분이 실행된다.
  • ch는 Parent 변수로 되어 있지만, Child 생성자로 만든거라서 엄연히 Child 클래스의 Object이다.
  • 그래서 ch.work() 실행하면 Child 클래스의 work 메소드(아래)가 실행된다.
@Override
public void work()
{
  System.out.println("I have to do my homework.");
  super.work();
}
  • 이후에 super.work()를 실행하면 superclass(Parent 클래스)의 work() 메소드가 실행된다.
public void work()
{
   System.out.println("I have to clean my kitchen.");
   rest(); // 이 부분이 중요! (subclass? superclass?)
}
  • 이후에 rest() 가 실행될 때가 중요하다. ch는 Child의 object이므로 rest()는 Child의 rest() 메소드(아래)가 실행된다.
@Override
public void rest()
{
  System.out.println("I rest in my room.");
  super.rest();
}
  • 이후에 super.rest()는 superclass(Parent 클래스)의 rest() 메소드가 실행되고 완료된다.
[참고]
위 코드의 실행순서를 잘 이해하는 데에 도움이 되는 "자바 비주얼 디버거"라는  아래의 사이트를 이용해 보자.
-링크: https://cscircles.cemc.uwaterloo.ca/java_visualize/#

 

 

 

[유제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
class Base
{
    public void methodOne()
    {
        System.out.print("A");
        methodTwo();
    }
 
    public void methodTwo()
    {
        System.out.print("B");
    }
}
 
class Derived extends Base
{
    public void methodOne()
    {
        super.methodOne();
        System.out.print("C");
    }
 
    public void methodTwo()
    {
        super.methodTwo();
        System.out.print("D");
    }
}
public class Main {
  public static void main(String[] args) {
    Base b = new Derived();
    b.methodOne();
  }
}
cs

 

 

[유제3] 아래의 영문으로 된 조건에 맞는 코딩을 하세요.

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
class Customer
{
    private String name;
    private String address;
 
    public Customer(String n, String a)
    {
        name = n;
        address = a;
    }
 
    public String toString()
    {
        return "Name: " + name + "\nAddress: " + address;
    }
}
 
// 1.Complete the OnlineCustomer class to inherit from Customer
// 2.It should have an email attribute,
// 3.a constructor with 3 arguments (name, address, email) that uses the super
// constructor,
// 4.and an overridden toString() method that calls the super toString() method
//  and then prints "\nEmail:" and the email variable.
 
public class Main {
  public static void main(String[] args) {
    Customer c = new Customer("Fran Santiago""123 Main St., Anytown, USA");
    System.out.println(c);
 
    // 5.Uncomment these to test OnlineCustomer
    // OnlineCustomer c2 = new OnlineCustomer("Jasper Smith",
    //       "456 High St., Anytown, USA", "jsmith456@gmail.com");
    // System.out.println(c2);
  }
}
cs

 

 

[3] 요약

  • super 키워드는 superclass 생성자(constructor)와 메소드(method)를 실행시키는 데에 사용된다.
  • superclass의 메소드는 subclass에서 super.method()에 의해 실행될 수 있다.

 


 

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

더보기

[유제1 정답]

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
class Person {
    private String name = null;
    public Person(String theName) {
        name = theName;
    }
 
    public String getFood() {
        return "Hamburger";
    }
}
 
class Student extends Person {
    private int id;
    private static int nextId = 0;
    public Student(String theName) {
        super(theName);
        id = nextId;
        nextId++;
    }
 
    public String getFood() {
        String output = super.getFood();
        return output + " and Pizza";
    }
 
    public int getId() {
        return this.id;
    }
 
    public void setId(int theId) {
        this.id = theId;
    }
}
 
class Vegan extends Student {
  public Vegan(String name) {
    super(name);
  }
 
  @Override
  public String getFood() {
    String output = super.getFood();
    return "No," + output + " but Tomato.";
  }
}
 
public class Main {
  public static void main(String[] args) {
    Student p = new Student("Javier");
    System.out.println(p.getFood());
 
    Vegan v = new Vegan("Tom");
    System.out.println(v.getFood());
  }
}
cs

 

 

[유제2 정답]

 

 

[유제3 정답]

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
class Customer
{
    private String name;
    private String address;
 
    public Customer(String n, String a)
    {
        name = n;
        address = a;
    }
 
    public String toString()
    {
        return "Name: " + name + "\nAddress: " + address;
    }
}
 
// 1.Complete the OnlineCustomer class to inherit from Customer
// 2.It should have an email attribute,
// 3.a constructor with 3 arguments (name, address, email) that uses the super
// constructor,
// 4.and an overridden toString() method that calls the super toString() method
//  and then prints "\nEmail:" and the email variable.
class OnlineCustomer extends Customer
{
  private String email;
  
  public OnlineCustomer(String name, String address, String email) {
    super(name, address);
    this.email = email;
  }
 
  @Override
  public String toString() {
    return super.toString() + "\nEmail:" + email;
  }
 
}
 
public class Main {
  public static void main(String[] args) {
    Customer c = new Customer("Fran Santiago""123 Main St., Anytown, USA");
    System.out.println(c);
 
    // Uncomment these to test OnlineCustomer
    OnlineCustomer c2 = new OnlineCustomer("Jasper Smith",
          "456 High St., Anytown, USA""jsmith456@gmail.com");
    System.out.println(c2);
  }
}
cs

 


 

728x90
반응형

댓글