0

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().

What
  • 195
  • 10
  • If name is to be publicly accessible, use the 'public' access modifier. It shouldn't be protected according to your design. –  Dec 27 '15 at 16:33
  • 1
    Why do you need that? Can you bring real example/case when you'll need that. Maybe you're doing it all wrong at the first place. `protected` doesn't work that way. it goes from `up->down` that is from `base->inherited` not the other way around. – Michael Dec 27 '15 at 16:35
  • I have just used Name as instance.In my InheritedClass field that i want to access has to be protected. – What Dec 27 '15 at 16:35
  • 1
    What you're calling an "inherited" class doesn't in any way inherit from anything but `Object`. – T.J. Crowder Dec 27 '15 at 16:36
  • 1
    There is no "base" and "inherited" in "has-a" relationship. – Ivan Stoev Dec 27 '15 at 16:37

1 Answers1

1

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;
    }
}
Ahmed Anwar
  • 688
  • 5
  • 25