user3963687
user3963687

Reputation:

OOP concept of protected members of a class

I am reviving OOP concepts such as protected etc. using C#. Here is the problem:

// Demonstrate protected. 

using System;

class B
{
    protected int i, j; // private to B, but accessible by D 

    public void Set(int a, int b)
    {
        i = a;
        j = b;
    }

    public void Show()
    {
        Console.WriteLine(i + " " + j);
    }
}

class D : B
{
    int k; // private 

    // D can access B's i and j 
    public void Setk()
    {
        k = i * j;
    }

    public void Showk()
    {
        Console.WriteLine(k);
    }
}

class E : D 
{   //private
    int l;
    public void Setl() 
    {
        //using protected i,j
        l = i * j;
    }

    public void Showl()
    {
        Console.WriteLine(l);
    }
}

class ProtectedDemo
{
    static void Main()
    {
        D ob = new D();
        E e = new E();
        ob.Set(2, 3); // OK, known to D 
        ob.Show();    // OK, known to D 

        ob.Setk();  // OK, part of D 
        ob.Showk(); // OK, part of D

        e.Setl();
        e.Showl();
        Console.ReadKey();
    }
}

Why is e.Showl() showing '0' then it should be 6???

Upvotes: 2

Views: 88

Answers (3)

WholeLifeLearner
WholeLifeLearner

Reputation: 455

What really does your code:

D ob = new D(); // create D; i,j,k =0 (default value for int in c#)
E e = new E();  // create E; i,j,k,l =0
ob.Set(2, 3); // ob.i = 2, ob.j = 3 ; e.i and e.j still 0
ob.Show();    // 2 3

ob.Setk();  // ob.k=6 
ob.Showk(); // show 6
e.Setl();  //e.l = e.i* e.j  thus e.l=0*0=0
e.Showl(); //show 0
Console.ReadKey();

Values of object E are stored in another place than values of object D, even if they have the same name. If you want D.i and E.i to have the same value, use static keyword.

Secondly, initialize variables, that's a good practice in all cases, especially you cannot predict the proper outcome of your integers.

Protected keyword means accessible for subclass in a calling way. It does not mean that a subclass object have the same storage for variables.

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151594

Inheriting a member means a derived class will have this member, not that it will share its value with all parents and descendants (unless the member is static).

At E e = new E(); you initialize a new instance of E, which inherits from D and B but doesn't automagically share the field values of other instances. They would share those if these fields i and j were static.

When you do this:

E e = new E();
e.Set(21, 2);
e.Setl();
e.Showl();

The response will be 42.

Upvotes: 4

James
James

Reputation: 82096

E is a completely different instance than ob, although E derives from D it has no relationship with another instance of D.

If you want the result of Show to be 6 then you need to call Set(2, 3) on E i.e.

e.Set(2, 3);
e.Setl();
e.Showl();

Upvotes: 3

Related Questions