I have a non abstract class called 'Player', and an abstract class called 'Score' with a subclass of 'Combination'. Within Combination there is and abstract method used in further subclasses.
How can I call my abstract method from the non-parent method 'Player' without making them static?
// This is the abstract method within Combination,
// it uses the face values from rolled dice to calculate the score.
abstract public int CalculateScore(int[] faceValues);
//Array of 'Score's in Player
private Score[] scores = new Score[10];
You cannot. This is access modifier and it was designed to narrow access to a class. To use it in your case, I suggest to change accessibility from abstract
to public
of a Score
class.
If I understand you correctly, you want to implement CalculateScore
in your derived class by accessing the scores
field?
Simple answer is, you can't as you designed it that way. private
modifier makes sure, only your own class can access the field. If you want derived classes to have access to that field, you have to change your modifier to protected
on the scores
-field.
If you do not want your derived classes to have access to scores
directly, you have to implement methods with at least protected
access, that modify the scores
-field in a defined way, on the base class.
So your situation:
Player
is a normal classs Score
is an abstract class Combination
is an abstract class too that subclasses Score
. It contains an abstract method CalculateScore
that you want to call from inside the Player
class. Player
has an array of Score
s You can check if an element in your Score
array is of type Combination
then cast it.
if(score[0] is Combination)
{
(score[0] as Combination).CalculateScore(/* arguments here */);
}
You might need to rethink how your classes work though. IMHO, Player shouldn't be the one calculating the scores. Maybe use a ScoreCalculatorService
to handle that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.