본문 바로가기
카테고리 없음

상속자 부모와 자식 선언을 다르게 해줄 경우 차이(20220707 til2)

by 날파리1 2022. 7. 8.

오늘도 재미있는 경험을 했다.

클래스명 객체명 을 선언하면 클래스에 정의된 메소드를 무조건 불러올 수 있다고 생각했다.

위 말 그대로이다. 어떤 클래스를 선언과 동시에 생성하고 그 클래스명.메소드명() 하면 쓸 수 있다고 생각했다.

절반은 맞다. 근데 함정이 있는게 그 클래스가 부모클래스를 선언해도 빨간줄이 안떠서 헷갈리는 경우가 있다.
즉 해당 클래스의 부모클래스를 선언하고 객체를 만들면 해당클래스의 부모성질만 사용할 수 있다.

이게 무슨말이냐면  

import javax.swing.*;

public class TaskRegisterPanel extends JPanel {
  private JPanel taskPanel;
  private JTextField todoTextField;

  TaskRegisterPanel(JPanel taskListPanel) {

    JLabel label = new JLabel("할 일");
    this.add(label);

    todoTextField = new JTextField(10);
    this.add(todoTextField);

    JButton button = new JButton("추가");
    this.add(button);

    //할일 추가 버튼을 눌렀을 때 액션
    button.addActionListener(event -> {

      taskPanel = new TaskPanel(taskListPanel, todoTextField);

    });
  }

  public JPanel getTaskPanel() {
    return taskPanel;
  }
}

위와 같이 TaskRegisterPanel은 JPanel 을 상속받아 JPanel 의 성질을 가진다. 

그 말은 즉슨 TaskRegisterPanel을 JPanel로 선언하면 생성자(선언과 생성되자마자 바로 실행되는 메소드, 본인의 클래스명을 메소드명으로 사용하고 패러미터를 받을수 있음)의 기능만 사용할 수 있다. JPanel 은 패널로서 기능만 가지지 다른 메소드를 가지지 않으므로.

 

따라서 아래쪽의 게터 메소드를 사용하려면 반드시 이 패널을 TaskRegisterPanel로 선언해야한다.

예제1) 부모클래스 선언으로 부모클래스 외 기능 사용불가 에디터에서 빨간줄이 뜸

private JPanel taskRegisterPanel;


public static void main(String[] args) {
  ToDoList application = new ToDoList();
  application.run();
}

public void run() {
  taskRegisterPanel.getTaskPanel();

예제2) 본인의 클래스로 선언해서 사용가능 

private TaskRegisterPanel taskRegisterPanel;


public static void main(String[] args) {
  ToDoList application = new ToDoList();
  application.run();
}

public void run() {
  taskRegisterPanel.getTaskPanel();

여기까지이

 

소소하게 상속자 관련  짤하나 

댓글