java 两个类调用函数调用函数调用函数,如何从Java中的另一个类调用方法

本文探讨如何在Java类Invoice中利用Product对象的getID()方法作为HashMap的键,并询问是否可以一次性为HashMap添加name, info, quantity三个属性。解答指出可以直接通过Product对象引用调用其方法,并质疑为何需要额外方式处理已有的Product对象属性。
摘要由CSDN通过智能技术生成

So, I have this class:

public class Product {

private String name, id, info ;

private int quantity;

public Product(String newName, String newID, String newInfo, Integer newQuantity){

setName(newName);

setID(newID);

setPrice(newInfo);

setQuantity(newQuantity);}

public void setName(String name) {

this.name = name; }

public void setID(String id) {

this.id = id; }

public void setPrice(String info) {

this.info = info; }

public void setQuantity(Integer quantity) {

this.quantity = quantity; }

public String getID( ) {

return id; }

public String getName( ) {

return name; }

public String getInfo( ) {

return info; }

public int getQuantity( ) {

return quantity; }

In another class i have this:

public class Invoice implements Group {

private HashMap prod = new HashMap( );

public Invoice(){ }

public void addProd(Product a) {

prod.put(??getID()??,new Product(??));

}

}

If this data was user generated rather than me, I would use the getID() method right?

So in my class invoice, how do i use the method getID(), so that I can use it in the parameter for my key value in the HashMap? Also is there a way to add 3 values (name info quan) to the hashmap without making a new class?

解决方案

I see that you get Product object with ref "a" as parameter to your addProd method.

And you can get id by just using a.getID(). It should look as:

public void addProd(Product a) {

prod.put(a.getID(),a);

}

I didn't understand second part of your question.. I think you already have 3 values in your Product object and you put Product object to Map, So why do you require another way ?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值