简体   繁体   English

为什么我不需要创建一个对象?

[英]Why don't I need to create an object?

import javax.swing.JoptionPane;

class Hat
{
  public static void main(String[]args)
   {

      String fn = JOptionPane.showInputDialog("Enter first number");
      String sn = JOptionPane.showInputDialog("Enter second number");

      int num1 = Integer.parseInt(fn);

      int num2 = Integer.parseInt(sn);

      int sum = num1 + num2;

      JOptionPane.showMessageDialog(null,"The answer is " +sum,"the title");
   }
}

Why is it not necessary to create an object in order to use showInputDialog method from the JOptionPane class?为什么不需要创建对象来使用 JOptionPane 类中的 showInputDialog 方法? Why is null used in showMessageDialog method?为什么在 showMessageDialog 方法中使用 null?

The showMessageDialog method is static and therefore exists on the class not on an instance. showMessageDialog方法是static ,因此存在于类而不是实例上。 Here is a little more explanation about static methods这里是关于静态方法的更多解释

The first parameter is the parent which specifise relative to which other Frame the OptionPane belongs.第一个参数是父级,它指定相对于 OptionPane 所属的其他 Frame。 If it is null , the OptionPane is independent of any other Frame.如果为null ,则 OptionPane 独立于任何其他 Frame。 See the documentation 查看文档

> parentComponent - determines the Frame in which the dialog is
> displayed; if null, or if the parentComponent has no Frame, a default
> Frame is used

Because showInputdialog is a static method.因为showInputdialog是一个静态方法。 It is not logically attached to an object.它在逻辑上不依附于对象。 It is rather a functionality exposed by the class itself.它是类本身公开的功能。

All methods/variables used in that method are either method scoped or static.该方法中使用的所有方法/变量都是方法范围的或静态的。 JOptionPane.showMessageDialog() for example is static, while num1/num2 are all method scoped.例如 JOptionPane.showMessageDialog() 是静态的,而 num1/num2 都是方法范围的。

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

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