如何从Java中的另一个类调用方法 [英] How to call a method from another class in Java
问题描述
所以,我有这个类:
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; }
在另一个类中,我有:
public class Invoice implements Group<Product> {
private HashMap<String, Product> prod = new HashMap<String, Product>( );
public Invoice(){ }
public void addProd(Product a) {
prod.put(??getID()??,new Product(??));
}
}
如果此数据是用户生成的,会使用 getID()
方法吗?
所以在我的类发票,我如何使用方法 getID()
,以便我可以使用它的参数中的我的键值在HashMap?还有一种方法来添加3个值(名称信息量)到hashmap而不创建一个新类?
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?
推荐答案
您将获得产品
对象与参数 a
作为您的 addProd
方法。
I see that you get Product
object with ref "a
" as parameter to your addProd
method.
您可以通过使用a.getID()获取id。它应该看起来像:
And you can get id by just using a.getID(). It should look as:
public void addProd(Product a) {
prod.put(a.getID(),a);
}
我不明白你问题的第二部分。在您的Product对象中有3个值,并将Product对象放到Map中,那么为什么需要另一种方法呢?
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 ?
这篇关于如何从Java中的另一个类调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!