我有这段代码:
public class Barrier
{
private Car myCar;
private Sensor mySensor;
private Card myCard;
public Barrier()
{
myCar = new Car();
mySensor = new Sensor();
myCard = new Card();
}
}
和此代码
public class Card
{
private int Card1;
public void get_no_card(int result)
{
Card1 = result;
}
public void display()
{
if (Card1 == 1)
{
System.out.println("Card is present");
}
}
我想将Card类中的变量Card1调用到Barrier类中,以便屏障类可以输出Card以及卡类,我该怎么做呢?
答案 0 :(得分:0)
我希望我能正确理解你。 首先是障碍类:
public class Barrier {
private Car myCar;
private Sensor mySensor;
private Card myCard;
public Barrier() {
myCar = new Car();
mySensor = new Sensor();
myCard = new Card();
}
public void callCard() {
myCard.setCard1(1);
myCard.display();
System.out.println("The class type of myCard is " + myCard.getClass().getName());
}
}
卡片类:
public class Card {
private int Card1;
public void display() {
if (getCard1() == 1) {
System.out.println("Card is present");
}
}
public int getCard1() {
return Card1;
}
public void setCard1(int card1) {
Card1 = card1;
}
}
测试一下:
class Test {
public static void main(String[] args) {
Barrier b = new Barrier();
b.callCard();
}
}
因此,当我们调用callCard()
方法时,我们首先将Card1
的值设置为1,以便display()
将打印文本。然后我们打印myCard的类类型的名称。