What
What

Reputation: 195

Has-a relationship encapsulation

Is it somehow possible that base class can access fields in inherited class (has-a relationship)?

class BasicClass
{
    public InheritedClass objTemp = new InheritedClass();
    public BasicClass()
    {
    //Now i want to get some information from objTemp fields.
    //But Name is protected, what should I do here?
        objTemp.Name.Length();
    }
}
class InheritedClass
{
    protected string Name;
}

Maybe there are some tricky things that I don't know how to manage, or maybe it is better to create some more clever class hierarchy. Anyway thank you in advance. Sorry for missunderstanding.In few words i have class Game which consist another class WordsContainer.

 class Game
{
    private Player objGamer;
    private WordsContainer objWordsClass = new WordsContainer();
    public Game()
    {
        Console.Title = "Hangman";
        Console.Write("Player name information:");
        string localName = Console.ReadLine();
        objGamer = new Player(localName);
        StringBuilder bumpWord = new StringBuilder(objWordsClass.getKeyWord().Length);

    }
class WordsContainer
{
    /// <summary>
    /// WordsContainer class contains a list of strings from wich with getKeyWord method
    /// we could get string type key.
    /// </summary>
    private List<string> wordBank = new List<string>() {"stack","queue","heap","git","array"};
    public WordsContainer(){}
    public string getKeyWord()
    {
        Random random = new Random((int)DateTime.Now.Ticks);

        return wordBank[random.Next(0, wordBank.Count)];
    }

So is it possible in this way somehow hide public string getKeyWord().

Upvotes: 0

Views: 479

Answers (1)

Ahmed Anwar
Ahmed Anwar

Reputation: 678

If you want to keep going on the code you have now, you could just define a public string GetName() function in InheritedClass and call it from the object that you create in the BasicClass

class BasicClass
{
    public InheritedClass objTemp = new InheritedClass();
    public BasicClass()
    {
        int nameLength = objTemp.GetName().Length();
    }
}
class InheritedClass
{
    protected string Name;
    public string GetName()
    {
        return Name;
    }
}

Upvotes: 1

Related Questions