首页 > 解决方案 > 如何使用java中的构造函数返回一个类?

问题描述

如何返回这个Customer类,以便我可以在另一个类中使用这个类。

如果我使用static而不是void那么我无法从构造函数调用客户事务。

我尝试编写 new 关键字,但它不起作用,但这正在返回一个类:

import java.util.ArrayList;

public class Customer  {
        private String name;
        private ArrayList<Double> customerTranscation;

    public Customer(String name) {
        this.name = name;
        this.customerTranscation = new ArrayList<Double>();
    }
    public String getName() {
        return name;
    }

    public ArrayList<Double> getCustomerTranscation() {
        return customerTranscation;
    }

    public void newCustomerTran(String name,double amount){
        this.customerTranscation.add(amount);
         this.name = name;

    }
}

我怎样才能返回Customer类,以便我可以在另一个类中使用它?

标签: java

解决方案


在你的第二类中,你必须首先创建客户类的对象。喜欢Customer c=new Customer(“abc”);

这将初始化 CustomerTransaction 列表。

然后调用c.newCustomerTrans(“name”).which 将从您的第二个类调用 newCustomeTrans 方法。

如果您希望返回一个客户对象。做 。!

public Customer newCustomerTrans(String name ,double amount){
//create a new object p of Customer using new
//set name to p
//initialise and set customer trans arraylist to p
// return p 
}

这样您就可以使用第二类中的客户类详细信息..


推荐阅读