简体   繁体   English

缺少返回类型且没有空的方法?

[英]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(). 这段代码在我的教科书中,但是我不理解的是方法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 请在此处查看文档-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). 方法将始终具有return-type或void(无返回值)。

That is not a Method (which is a function attached to a class), but rather a Constructor . 那不是Method (它是附加到类的函数),而是Constructor Constructors are used to instantiate or "create" objects/classes. Constructors用于实例化或“创建”对象/类。

These resources should help you farther understand them: 这些资源应帮助您进一步了解它们:

Constructor: http://www.leepoint.net/notes-java/oop/constructors/constructor.html 构造函数: http : //www.leepoint.net/notes-java/oop/constructors/constructor.html

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

It's a constructor for the object TestPanels . 它是对象TestPanels的构造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() . 在诸如TestPanels t = new TestPanels()类的语句中调用它会创建一个具有9个JButton的对象,以及在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". 基本上,这是一种初始化对象属性的方法,就像JButton b = new JButton("Button")会给您一个带有“ Button”的按钮一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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