2010-11-01 62 views
1

嗨,我是新来的Java编程。我有一个类的实例变量,我应该叫另一个class.It不应该是静态按照下面给出##`在另一个类中调用一个类的变量?

public class Card { 

    private String no; 
    private String text; 
    public Vector totalCards = new Vector(); 

    public String getNo() { 
     totalCards.addElement(no); 
     return no; 
    } 

    public void setNo(String no) { 
     this.no = no; 
    } 

    public String getText() { 
     totalCards.addElement(text); 
     return text; 
    } 

    public void setText(String text) { 
     this.text = text; 
    } 
} 

我需要通过这个“totalCards”向量在requirements.The代码另一个类没有把它作为一个static.How我可以通过这个值。可以帮助我的任何人。任何建议感激。

+0

另一个类中的方法是否需要接受“Vector”作为参数?请更清楚你需要做什么。 – brumScouse 2010-11-01 21:09:53

+0

如果这是家庭作业,你应该这样做,但作为一个快速的家庭作业回答,你为其他两个变量创建了setter和getters,为什么不为totalCards做同样的事情呢? – 2010-11-01 21:10:06

回答

1

这是一个有点不清楚你的问题是什么,但你首先需要有卡的实例。然后totalCards Vector将存在于该Card对象中。

Card myCards = new Card(); 

现在访问myCards可以访问矢量对象:

myCards.totalCards 

然而,它被认为是一个更好的做法被许多人用来做totalCards私人,让一个getter它:

myCards.getTotalCards(); 
+0

谢谢Micheal它工作正常。 – MuraliN 2010-11-01 22:09:59

0

您可以简单地将totalCards引用传递给其他类,因为它是公共的。告诉我们更多关于客户类的信息谢谢。

3

因为变量“totalCards”是公开的,所以它可以通过卡片的一个实例直接访问。

0
public class Card { 
    private String no; 
    private String text; 
    /* initializing totalCards here is bad, why are you doing this here? If each 
     card has a list of totalCards, consider doing this in the constructor of a 
     Card */ 
    private Vector<Card> totalCards = new Vector(); 

    public String getNo() { 
     //getters should not have side effects like addElement... 
     totalCards.addElement(no); 
     return no;   
    } 

    public Vector<Card> getCards() { 
     return totalCards; 
    } 

    public void setNo(String no) { 
     this.no = no; 
    } 

    public String getText() { 
     //getters should not have side effects like addElement... 
     totalCards.addElement(text); 
     return text; 
    } 

    public void setText(String text) { 
     this.text = text; 
    } 

} 
0

其他职业需要有一个Card的实例。例如,通过创建一个新的实例:

public class TheOtherClass { 
    private Card myCard = new Card(); 

    public void doSomething() { 
     myCard.totalCards.doAnotherThing(); 
    } 
} 

顺便说一句:它被认为是不好的风格直接访问其他类的属性 - 尝试使用getter和setter方法:

public class Card { 
    private Vector<Card> totalCards = new Vector(); 
    public void getTotalCards() { 
     return totalCards; 
    } 
} 
1

您只需编写您的课程:

public class AnotherClass 
{ 
    public Class obj1 = new Class(); 


public String getNo() 
{ 
    Vector v1 = obj1.totalCards; 
    return v1; //or what do you want 
} 
相关问题