views:

277

answers:

5

Why the following program prints

B
B

(as it should)

public class A
    {
        public void Print()
        {
            Console.WriteLine("A");
        }
    }

    public class B : A
    {
        public new void Print()
        {
            Console.WriteLine("B");
        }

        public void Print2()
        {
            Print();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var b = new B();
            b.Print();
            b.Print2();
        }
    }

but if we remove keyword 'public' in class B like so:

    new void Print()
    {
        Console.WriteLine("B");
    }

it starts printing

A
B

?

+18  A: 

When you remove the public access modifier, you remove any ability to call B's new Print() method from the Main function because it now defaults to private. It's no longer accessible to Main.

The only remaining option is to fall back to the method inherited from A, as that is the only accessible implementation. If you were to call Print() from within another B method you would get the B implementation, because members of B would see the private implementation.

Joel Coehoorn
+4  A: 

You're making the Print method private, so the only available Print method is the inherited one.

bdukes
+3  A: 

Externally, the new B.Print()-method isn't visible anymore, so A.Print() is called.

Within the class, though, the new B.Print-method is still visible, so that's the one that is called by methods in the same class.

Lennaert
+2  A: 

when you remove the keyword public from class b, the new print method is no longer available outside the class, and so when you do b.print from your main program, it actually makes a call to the public method available in A (because b inherits a and a still has Print as public)

Raj
+1  A: 

Without the public keyword then the method is private, therefore cannot be called by Main().

However the Print2() method can call it as it can see other methods of its own class, even if private.

samjudson