Reputation: 5
I am trying to write some code (novice java user here) and I'm getting an error. I have a hunch that it has something to do with my class definition for AdvancedMatch, which is a match in a tournament. It needs to have two feeder matches, which can be either an AdvancedMatch or an InitMatch, where InitMatch has no feeders and AdvancedMatch does. To achieve this I used an interface, ITournament, which gives me the option to have ITournament inside my data structure of AdvancedMatch.
public class AdvancedMatch implements ITournament {
MatchData data;
ITournament feeder1;
ITournament feeder2;
AdvancedMatch (MatchData data, ITournament feeder1, ITournament feeder2) {
this.data = data;
this.feeder1 = feeder1;
this.feeder2 = feeder2;
}
}
public class InitMatch implements ITournament {
MatchData data;
InitMatch (MatchData data) {
this.data = data;
}
}
interface ITournament {
public Boolean allScoresValid();
public Boolean highCapacityVenue(int ticketsSold);
public Boolean winnerAlwaysAdvanced();
public Boolean tWinnerContestant1() ;
}
Later in the code, I try to call feeder1.data within a method, and I keep getting the error that the data cannot be resolved or is not a field. This confuses me, as clearly data is part of both AdvancedMatch and InitMatch.
public Boolean winnerAlwaysAdvanced() {
if (this.feeder1.tWinnerContestant1()) {
this.data.dCompareContestants1(this.feeder1.data);
}
else
return this.data.dCompareContestants2(this.feeder1.data);
}
}
Any help would be appreciated.
Upvotes: 0
Views: 68
Reputation: 14810
Your feeder1 is declared as an ITournament ITournament feeder1;
— it is not declared as an InitMatch
which has the data
attribute.
When a variable is declared using an interface it can only access things declared in the interface, regardless of the underlying class instance.
Since both InitMatch and AdvancedMatch do have the data element, you can include that in your interface definition. Best practices would call for a "getter" however, instead of direct access.
interface ITournament {
public Boolean allScoresValid();
public Boolean highCapacityVenue(int ticketsSold);
public Boolean winnerAlwaysAdvanced();
public Boolean tWinnerContestant1();
public MatchData getMatchData();
}
Upvotes: 1
Reputation: 5087
For a class to implement an interface, it must implement all the methods of the interface.
Neither of your class implement all methods of the ITournament
interface.
Upvotes: 0