Java Tutorial - lesson three


Lesson Three: Putting code into methods.

previous lesson - back to tutorial index - next lesson


Change your class Calculator into:

import java.awt.*;
import java.awt.event.*;
//---------------------------------------------
// Class
//---------------------------------------------
public class Calculator extends Frame {
//---------------------------------------------
// Constructor
//---------------------------------------------
    public Calculator() {
        initScreen();
        System.out.println("Constructing a new Calculator...");
    }
//---------------------------------------------
// Methods
//---------------------------------------------
    private void initScreen() {
        this.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0); } });
        this.setBounds(100, 100, 300, 200);
        this.show();
        System.out.println("End of the method initScreen...");
    }
}

 

Save, compile and execute as in the previous lesson.

Nothing new with respect to the last lesson. We merely put some of the code that was located in the constructor in a method (equivalent to procedure or subroutine in other languages) and we called this method in the constructor. It makes it all far more readable.

Reviewing the code:
We added our own method initScreen(). Methods start with a lower-case letter by convention. Methods and variables can be private, protected or public. We will go into these identifiers in another lesson later. The word ´void´ means that the method does not return a value. In one of the next lessons, we will experiment with this issue.

previous lesson - back to tutorial index - next lesson