java - 提供编写构造函数的帮助

标签 java constructor

我正在参与一个小组项目,其任务是向现有程序添加构造函数。问题是,我不确定我的队友在问什么。下面是聊天截图 -

showing image

我应该在其中创建一个构造函数:

public class UserMenu extends JFrame {

    private JPanel contentPane;
    private String a = "";
    private UserInfo user;
    /**
     * Launch the application.
     */

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UserMenu frame = new UserMenu(testUser.tes(testUser.tUser));
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

在引用“UserInfo”时(单独的java文件):

public class UserInfo {
    private String firstname;
    private String lastname;
    private String username;
    private String password;
    private String email;
    private double Checkings = 0.0;
    private double Savings = 0.0;
    private boolean hasCheckings = false;
    private boolean hasSaving = false;
    public Loan loan;

    public UserInfo(String firstname, String lastname, String username, String password, String email) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.username = username;
        this.password = password;
        this.email = email;
    }
}

最佳答案

什么是构造函数:

Constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and method are different. People often refer constructor as special type of method in Java.

构造函数与类具有相同的名称,在 Java 代码中看起来像这样。

public class MyClass{
   //This is the constructor
   MyClass(){
   }
   ..
}

您的案例:

在您的情况下,构造函数将如下所示:

public class UserMenu extends JFrame {

    private JPanel contentPane;
    private String a = "";
    private UserInfo user;
    /**
     * Launch the application.
     */

    public UserMenu(JPanel contentPane, String a, UserInfo user){

        this.contentPane = contentPane;
        this.a = a;
        this.user = user;
    }

[...] //rest of the code

如果你想了解更多信息可以查看Constructors in Java

关于java - 提供编写构造函数的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61629818/

相关文章:

java - 无法使用 Spring Boot 和 Thymeleaf 进行验证

java - 具有重复错误方法的 Ruby 变体

C++ 避免构造对象

c++ - 为什么内联构造函数和析构函数在 C++ 中不是一个好主意?

java - 我可以将 Class.newInstance() 与构造函数参数一起使用吗?

java - NetBeans IDE 8.0.2 支持 Netbeans IDE 7

java - org.eclipse.jdt.core.dom.AST 的 API 使用示例

Java 泛型转换为通配符规则

java形式继承从 super 构造函数调用错误的方法

groovy - Guice、Groovy、@Canonical 和继承不能很好地结合在一起