Search code examples
c#inheritanceencapsulation

Can't figue out why the value didn't change


I'm new to OOP and C#.

I've tried to use inheritance and encapsulation concepts and get stuck.

Can't figue out why a Deposit method din't work when i call it through Atm_1 class.


parent class

  class Atm
  {

    public int TotalBalance { get; private set; } = 1000;

    public Atm() { }

    public void DepoSit(int deposit)  { TotalBalance += deposit; }  

  }

child class

  class Atm_1:Atm 
  {

  }

main

 class Program
 {

    static void Main()
    {


        var atm = new Atm();
        var atm_1 = new Atm_1();

       //Before Deposit 
        Console.WriteLine("Total Balance is "+atm.TotalBalance);     //1000

        //Deposit
        atm_1.DepoSit(20);

        //After Deposit
        Console.WriteLine("Total Balance is " + atm.TotalBalance);   //Still 1000 ??



        atm.DepoSit(500);
        Console.WriteLine("Total Balance is " + atm.TotalBalance);   //Now 1500
        //This Works -why the above didn't work?  

    }
}

Solution

  • Atm_1 inherited the property TotalBalance , constructor Atm(), and method DepoSit(int deposit) of Atm, but not the data you set to new Atm();.

    Atm_1 and Atm are two different instances of the same class. Try to visualize your objects Amt_1 and Amt as variables, setting one variables data doesn't change the others data.