I just feel like I'm not doing this correctly and I have researched and just can't seem to wrap my head around how to initialize variable that have to reference another method or class.
Player class
public class Player
{
//instance variables
private String name;
private ScoreCard card;
private int fullDriveYards;
private int fullDrives;
private int drivesOnTarget;
}
Here's the ScoreCard class variables
public class ScoreCard
{
private int totalStrokes;
private int versusPar;
private LinkedList<Integer> playerScoreCard;
}
So this is how I have initialized the instance variables is Player class I did not code the Scorecard class as I didn't have to but I still added it so you can see what's going on. I just need to know if I am on the right track or completely off.
// Constructor for objects of class Player
public Player(String PlayerName)
{
// initialize all instance variables
// look for and handle a null reference for playerName
// to initialize this.card create ScoreCard instance and assign reference
this.name = PlayerName;
PlayerName = "UNKNOWN";
ScoreCard card = this.card;
this.card = new ScoreCard();
this.longestDrive = 0;
this.fullDriveYards = 0;
this.fullDrives = 0;
this.drivesOnTarget = 0;
}
It's correct, there are just some inconsistencies, so you may not get the result you're looking for.
In your constructor method for Player, you are assigning PlayerName to the name field, and then subsequently assigning PlayerName to "UNKNOWN".
Assigning PlayerName will have no effect on name.
In your comment you mention,
You'll need a conditional statement for this.
Furthermore, you are assigning your class variable card to a new local variable card.
This, again, will have no effect, since this.card would be null at this point.
The following will suffice.
So, the complete constructor should look like the following.
You're assignment is correct,
Since you're ScoreCard class variables are declared as private, you won't be able to access them via dot-notation—e.g., card.totalStrokes.
You will need to either remove the modifier, change the modifier to public, or create methods that will provide the access.
Then, you can access the values as follows.
Here are some references by Java which may help in your coding process.
Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects).
Lesson: Object-Oriented Programming Concepts (The Java™ Tutorials > Learning the Java Language).