대학수업/프로그램설계방법론

[06] 프로그램 설계 방법론(생성자와 필드 변수)

MIRIP 2022. 9. 22. 14:39
반응형

주제 : 생성 메서드와 필드 변수


생성 메서드(constructor method) : 객체가 태어나면서 저절로 한번 실행하는 메서드를 뜻한다.

생성 메서드를 만들 때는 클래스 이름과 동일하게 만든다.

public class ClassName {
    public ClassName(<type_1> par_1, …,<type_n> par_n) {
        // 몸체 코드 블록
    }
}

실습 : 아날로그 시계를 만들어보자

 

import javax.swing.*;

public class ClockWriter extends JPanel{
	
    public ClockWriter() {
        JFrame frame = new JFrame();
        frame.setTitle("Clock");
        frame.setSize(300, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
	public static void main(String[] args) {
		new ClockWriter();
		return;
	}
}

먼저 아래 사진과 같이 앱을 만들기 위한 판을 만들었다.

JFrame으로 그린 판

여기에 코드를 추가하여 글씨와 네모를 그려보았다.

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.*;

public class ClockWriter extends JPanel{
	
    public ClockWriter() {
        JFrame frame = new JFrame();
        frame.setTitle("Clock");
        frame.setSize(300, 400);
        frame.getContentPane().add(this);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public void paintComponent(Graphics g) {
    	g.setColor(Color.blue);
    	g.drawString("TIME IS GOLD", 105, 50);
    	g.fillRect(25, 100, 250, 250);
    }
	public static void main(String[] args) {
		new ClockWriter();
		return;
	}
}

위의 결과는 다음과 같다. 

field변수 : 클래스 내부에서만 사용할 수 있도록 public 대신 private을 사용한다.

외부에서 field변수를 사용하고 싶다면 메서드를 이용하여 호출한다.

 

다음을 실행하면 시계의 틀을 그릴 수 있다.

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.*;

public class ClockWriter extends JPanel{
	
	private final int SIZE;
	
    public ClockWriter(int _s) {
    	SIZE = _s;
        JFrame frame = new JFrame();
        frame.setTitle("Clock");
        frame.setSize(SIZE+50, SIZE+150);
        frame.getContentPane().add(this);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public void paintComponent(Graphics g) {
        g.setColor(Color.BLUE);
        g.drawString("TIME IS GOLD", 105, 50);
        g.setColor(Color.LIGHT_GRAY);
        g.fillOval(20, 100, 250, 250);
    }
	public static void main(String[] args) {
		new ClockWriter(250);
		return;
	}
}

다음 시간에 실습을 마저하겠다.

728x90
반응형