Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Private Visibility and inheritance


The program that we discuss is the following:

using System;

public class A{
  private int i = 7;

  protected int F(int j){
   return i + j;
  }
}

public class B : A{
  public void G(){
    Console.WriteLine("i: {0}", i);
    Console.WriteLine("F(5): {0}", F(5));
  }
}

public class Client {
  public static void Main(){
    B b = new B();
    b.G();
  }
}

An instance of B has an instance variable i, inherited from class A, but i is not visible in B.

The method F from class A is also inherited by class B. F is protected in A, and therefore it is visible and applicable in the method G.

The first WriteLine in G is illegal, because i is invisible in class B. The second WriteLine is OK, because F is visible in class B.

In order to compile the program, you must eliminate the first WriteLine in G.

As expected, the output of the modified program is

F(5): 12