Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - field is not visible

Tags:

java

field

As part of my homework I have been given an already prepared public static void main method. My job is to supplement this by creating all the methods relevant for this. This should be done in three other classes.

In the already prepared main method, there is the following code:

ticket = new LotteryTicket(10);
ticket.ticketOwner = new Player();

LotteryTicket and Player are other classes created by me. Relevant instance variables in the LotteryTicket class are:

private LotteryRow[] rows;
private Player ticketOwner;

public LotteryTicket(int maxNumberOfRows) {
    this.rows = new LotteryRow[maxNumberOfRows];
}

Player is, as mentioned, another class I have created. In this class there is, among other things, a method for the user to input data such as name, address, postal code, etc.

When I try to run the program, I get an error in the ticket.ticketOwner = new Player(); line. The error is: "The field LotteryTicket.ticketOwner is not visible"

What can be the cause of this? I would greatly appreciate any help! I hope the code I have provided is sufficient. I have not encountered this error message before, so I am at a loss about what to do.

like image 465
Kristian Avatar asked Dec 02 '22 01:12

Kristian


1 Answers

The core of the problem is that the field (ticketOwner) you are trying to access is marked private. Also, at least from whatever we see, there seems to be missing getter/setters for accessing it.

While a quickfix for this is to add getter/setters and access the field using them, or an ugly way is to make the field public. But you would want to read on...

Your best bet (if a Player is necessary for a LotteryTicket, which seems so) is to have the Player instance in the constructor of LotteryTicket itself, so there is no additional overhead.

public LotteryTicket(int maxNumberOfRows, Player player) {
        this.rows = new LotteryRow[maxNumberOfRows];
        this.ticketOwner = player;
}

EDIT

Your invocations would look like this:

Player p = new Player();
// invoke APIs on (Player p), if needed
ticket = new LotteryTicket(10, p);
like image 197
Saket Avatar answered Dec 20 '22 03:12

Saket