Reputation: 51
I am wondering how do you access an argument created in a different class?
What I have:
public class Card {
private final int cardNumber;
private String cardName;
private final String cardOwner;
private final boolean isCredit;
private double balance;
public Card(int cardNumber, String cardName, String cardOwner, boolean isCredit, double balance) {
this.cardNumber = cardNumber;
this.cardName = cardName;
this.cardOwner = cardOwner;
...
}
I want to access the argument cardOwner
in the following way:
public void add(Card[] newCards) {
if (cardOwner == owner) {
...
}
}
but I am not sure on how to go about doing that?
Upvotes: 0
Views: 30
Reputation: 58848
You can't access arguments outside the method they're in. Full stop.
What you can do is access the fields (which in your code have the same name as the constructor arguments. I recommend not giving different things the same name until you understand them well).
If you want to access the field cardOwner
from inside the Card
class, you can just use its name.
If you want to access the field cardOwner
from outside the Card
class, you will first need to decide which card you want to get the owner of. If you have a reference to a card (call it card
), then you can use card.cardOwner
to get that card's owner.
However, private
members (fields/methods/constructors) can only be accessed from within the same class (that is the entire point of private
). You could either make the field public
instead, or add another way to access the field's value, such as a small public
method:
public String getCardOwner() {
return cardOwner;
}
Upvotes: 1