简体   繁体   中英

How to Create a simple atm program in c# using inheritance

I'm trying to create an e-ATM console app using C# using inheritance, but every time I debug I see that the derived class values are null , whereas the base class fields or properties are filled with values. Why is the derived class not showing the list with their data even after it is inherited from the base class?

class CreateAccount
{
    string firstName, lastName, dateOfBirth, phoneNO, fathersName, mothersName;
    double initialBalance; int pinNo = 100, accountNo = 1234, age; DateTime yearOfBirth;

    protected static List<CreateAccount> data = new List<CreateAccount>();

    protected string FirstName
    {
        get { return this.firstName; }
        set
        {
            if (string.IsNullOrEmpty(value)) throw new Exception();
            else firstName = value;
        }
    }
    protected string LastName
    {
        get { return this.lastName; }
        set
        {
            if (string.IsNullOrEmpty(value)) throw new Exception();
            else lastName = value;
        }
    }
    protected string DateOfBirth
    {
        get { return this.dateOfBirth; }
        set
        {
            if (string.IsNullOrEmpty(value)) throw new Exception();
            else dateOfBirth = value;
        }
    }
    protected string PhoneNo
    {
        get { return this.phoneNO; }
        set
        {
            if ((string.IsNullOrEmpty(value)) || value.Length != 10)
                throw new Exception();
            else
                phoneNO = value;
        }
    }
    protected string FathersName
    {
        get { return this.fathersName; }
        set
        {
            if (string.IsNullOrEmpty(value))
                throw new Exception();
            else
                fathersName = value;
        }
    }
    protected string MothersName
    {
        get { return this.mothersName; }
        set
        {
            if (string.IsNullOrEmpty(value))
                throw new Exception();
            else
                mothersName = value;
        }
    }
    protected double InititailBalance
    {
        get { return this.initialBalance; }
        set
        {
            if (double.IsNaN(value))
                throw new Exception();

            else
                initialBalance = value;
        }
    }
    protected int PinNo
    {
        get { return this.pinNo; }
    }
    protected int AccountNo
    {
        get { return this.accountNo; }
    }
    public void GenerateAccount()
    { 
         // code for asking user for their details.
        data.Add(this);
    }
}


class ATM :CreateAccount
{
    public void Deposit()
    {
        Console.WriteLine("Enter your account number");
        int accountNo = int.Parse(Console.ReadLine());

        if (accountNo == AccountNo)
        {
            Console.WriteLine("Enter your amount you wish to deposit");
            int amount = int.Parse(Console.ReadLine());
            InititailBalance+= amount;
        }
    }
}   


class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("Menu");
            Console.WriteLine("1.Create Account");
            Console.WriteLine("2.ATM");
            Console.Write("Please enter your selections: ");
            int select = int.Parse(Console.ReadLine());

            switch (select)
            {
                case 1:
                    CreateAccount account = new CreateAccount();
                    account.GenerateAccount();
                    break;

                case 2:
                    ATM atm = new ATM();
                    atm.Deposit();
                    break;

            }
        }
    }
}

You are creating two different objects: a 'CreateAccount' Object and an 'ATM' object. An ATM object does not automatically inherit the values from a previously created CreateAccount object, they are two completely different, unrelated entities.

So for your ATM object to have the same values that your CreateAccount object has, you would have to copy the CreateAccount object to your ATM object.

CreateAccount account = new CreateAccount();
//set account variables here
ATM atm = (ATM)account;

Here is how it's done with proper use of inheritance which is useless in this case actually. Dictionary is the proper datastructure to use in this case because you can avoid duplicates with it. Also from this code you might want to remove the accountNo from Account class to avoid duplicate numbers being kept and the ask it beffore calling GenerateAccount() method. So this is full console app:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ATM
{
    class Account
    {
        string firstName, lastName, dateOfBirth, phoneNO, fathersName, mothersName;
        double initialBalance; 
        int pinNo, accountNo, age; 
        DateTime yearOfBirth;

        public Account() 
        {
            pinNo = 100;
            accountNo = 1234;
        }

        public string FirstName
        {
            get { return this.firstName; }
            set
            {
                if (string.IsNullOrEmpty(value)) throw new Exception();
                else firstName = value;
            }
        }
        public string LastName
        {
            get { return this.lastName; }
            set
            {
                if (string.IsNullOrEmpty(value)) throw new Exception();
                else lastName = value;
            }
        }
        public string DateOfBirth
        {
            get { return this.dateOfBirth; }
            set
            {
                if (string.IsNullOrEmpty(value)) throw new Exception();
                else dateOfBirth = value;
            }
        }
        public string PhoneNo
        {
            get { return this.phoneNO; }
            set
            {
                if ((string.IsNullOrEmpty(value)) || value.Length != 10)
                    throw new Exception();
                else
                    phoneNO = value;
            }
        }
        public string FathersName
        {
            get { return this.fathersName; }
            set
            {
                if (string.IsNullOrEmpty(value))
                    throw new Exception();
                else
                    fathersName = value;
            }
        }
        public string MothersName
        {
            get { return this.mothersName; }
            set
            {
                if (string.IsNullOrEmpty(value))
                    throw new Exception();
                else
                    mothersName = value;
            }
        }
        public double InititailBalance
        {
            get { return this.initialBalance; }
            set
            {
                if (double.IsNaN(value))
                    throw new Exception();

                else
                    initialBalance = value;
            }
        }
        public int PinNo
        {
            get { return this.pinNo; }
        }
        public int AccountNo
        {
            get { return this.accountNo; }
        }
        public void GenerateAccount()
        {
            // code for asking user for their details.
        }
    }


    class ATM
    {
        public static Dictionary<int, Account> AccountsList;

        static ATM() 
        {
            AccountsList = new Dictionary<int, Account>();
        }

        public void CreateAccount()
        {
            Account acc = new Account();
            acc.GenerateAccount();
            AccountsList.Add(acc.AccountNo, acc);
        }

        public void Deposit()
        {
            Console.WriteLine("Enter your account number");
            int accountNo = int.Parse(Console.ReadLine());

            if (AccountsList.ContainsKey(accountNo))
            {
                Console.WriteLine("Enter your amount you wish to deposit");
                int amount = int.Parse(Console.ReadLine());
                AccountsList[accountNo].InititailBalance += amount;
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            ATM atm = new ATM();
            while (true)
            {
                Console.WriteLine("Menu");
                Console.WriteLine("1.Create Account");
                Console.WriteLine("2.ATM");
                Console.Write("Please enter your selections: ");
                int select = int.Parse(Console.ReadLine());

                switch (select)
                {
                    case 1:
                        atm.CreateAccount();
                        break;

                    case 2:
                        atm.Deposit();
                        break;
                    default:
                        Console.WriteLine("Invalid selection!");
                        break;
                }
            }
        }
    }
}

CreateAccount is an operation of Atm and this is why I don't think you should be using inheritance. I propose this solution:

Class Account:

class Account
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string PhoneNumber { get; set; }
    public double Balance { get; set; }

    // More properties here
    ...
}

Class Atm:

class Atm
{
    public List<Account> Accounts { get; set; }

    public Atm()
    {
        Accounts = new List<Account>();
    }

    public void CreateAccount()
    {
        var account = new Account();

        // Get details from user here:
        ...

        account.Balance = 0.0;
        account.Id = Accounts.Count + 1;

        Accounts.Add(account);
    }

    public void Deposit()
    {
        int accountId;

        // Get input from the user here:
        // --------------------------------
        // 1. Check that the account exists
        // 2. Deposit into the account.
        ...
    }

Full example:

class Program
{
    static void Main()
    {
        var atm = new Atm();
        while (true)
        {
            int option;

            Console.WriteLine();
            Console.WriteLine("Menu:");
            Console.WriteLine("1. Create Account");
            Console.WriteLine("2. Deposit");
            Console.WriteLine();
            Console.Write("Please make a selection: ");

            var input = int.TryParse(Console.ReadLine(), out option);

            Console.WriteLine("-----------------");

            switch (option)
            {
                case 1:
                    atm.CreateAccount();
                    break;
                case 2:
                    atm.Deposit();
                    break;
            }
        }
    }
}

class Account
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string PhoneNumber { get; set; }
    public double Balance { get; set; }
}

class Atm
{
    public List<Account> Accounts { get; set; }

    public Atm()
    {
        Accounts = new List<Account>();
    }

    public void CreateAccount()
    {
        var account = new Account();

        Console.WriteLine("Create a new account!");
        Console.WriteLine();
        Console.Write("Enter first name: ");
        account.FirstName = Console.ReadLine();
        Console.Write("Enter last name: ");
        account.LastName = Console.ReadLine();
        Console.Write("Enter date of birth: ");
        account.DateOfBirth = DateTime.Parse(Console.ReadLine());
        Console.Write("Enter phone number: ");
        account.PhoneNumber = Console.ReadLine();

        account.Balance = 0.0;
        account.Id = Accounts.Count + 1;

        Accounts.Add(account);
    }

    public void Deposit()
    {
        int accountId;

        Console.Write("Enter your account number: ");
        int.TryParse(Console.ReadLine(), out accountId);

        var account = Accounts.FirstOrDefault(a => a.Id == accountId);
        if (account != null)
        {
            double amount;
            Console.Write("Enter amount to deposit: ");
            double.TryParse(Console.ReadLine(), out amount);
            account.Balance += amount;
            Console.Write("Your new balance is {0}", account.Balance);
        }
        else
        {
            Console.WriteLine("That account does not exist!");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM