Wednesday, August 11, 2010

Are Private Members Inherited?

When I interview someone, I start the question phase with simple object-oriented questions to get a feel for the person. Am I interviewing someone who writes rote procedural code or do I have someone in front of me who thinks in terms of objects and relationships. Even more intriguing, am I talking to a functional wunderkind who will enlighten me in my own journey through code? I start off with the simplest of questions: what’s the difference between a class and an object? Of course, the topics usually end up deep into their own experience as I use technical questions for the response factor more than right or wrong answers. I’m more interested in the fact that someone is thoughtful, into programming, and able to learn rather than whether they memorized a textbook or interview prep site.
public class Person
{
   private string message;
   public override string ToString()
   {
       return message;
   }
   public static Person CreateEmployee()
   {
       return new Employee();
   }
   class Employee : Person
   {
       public Employee()
       {
           this.message = "I inherit private members!";
       }
   }
}
Run this within a Console application, and it will print the message on the screen: “I inherit private members!”
class Program
{
   static void Main()
   {
       Console.WriteLine(Person.CreateEmployee());
   }
}
Proof positive that private members are actually inherited. Remember, modifiers such as public, protected, private, and internal are all accessibility modifiers. These modifiers affect encapsulation rather than inheritance.
Read more: KodefuGuru