简体   繁体   中英

Methods lacking return types and no void?

This piece of code is in my textbook, but what I'm not understanding is the method TestPanels(). It has no return type AND no void. How can this happen?

public class TestPanels extends JFrame {

public TestPanels() { 
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(4,3));

    for (int i = 1; i <= 9; i++) {
        p1.add(new JButton(""+i));
    }

    p1.add(new JButton(""+0));
    p1.add(new JButton("Start"));
    p1.add(new JButton("Stop"));

    JPanel p2 = new JPanel(new BorderLayout());
    p2.add(new JTextField("Time to be displayed here"), BorderLayout.NORTH);
    p2.add(p1, BorderLayout.CENTER);

    add(p2, BorderLayout.EAST);
    add(new JButton("Food to be placed here"), BorderLayout.WEST); 

}

public static void main(String[] args) {
    TestPanels frame = new TestPanels();
    frame.setTitle("The Front View of a Microwave Oven");
    frame.setSize(400, 250);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true); 
}
}

Its a constructor and not a method. Please check the documentation here - http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

It is a constructor and not a method. Methods will always have return-type or void (no return value).

That is not a Method (which is a function attached to a class), but rather a Constructor . Constructors are used to instantiate or "create" objects/classes.

These resources should help you farther understand them:

Constructor: http://www.leepoint.net/notes-java/oop/constructors/constructor.html

Method: http://www.tutorialspoint.com/java/java_methods.htm

It's a constructor for the object TestPanels . Calling it in a statement such as TestPanels t = new TestPanels() would create an object with 9 JButton s, and all the other components created in TestPanels() .

It's basically a way to initiate the attributes of an object, same way as JButton b = new JButton("Button") would give you a button that says "Button".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM