計算機科学のブログ

encapsulation - Keep your privates… private - constructor, this keyword

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 5(encapsulation - Keep your privates… private)、p.265(Sharp your pencil)の解答を求めてみる。

コード

GumballMachine.cs

using System;
namespace MyFirstConsoleApp
{
    public class GumballMachine
    {
        private int gumballs;
        private int price;
        public int Price
        {
            get
            {
                return price;
            }
        }
        public GumballMachine(int gumballs ,int price)
        {
            this.gumballs = gumballs;
            this.price = price;
        }
        public string DispenseOneGumball(int price, int coinsInserted)
        {
            if (coinsInserted >= price)
            {
                gumballs--;
                return "Here's your gumball";
            }
            return "Insert more coins";
        }
    }
}