C# class, object, method, constructors, getter, setter, static


Mar 01, 2023

class (blueprint)

class is basically just a specification for a new data type, so it use to model real word entities inside of our program.

In other words class is like blueprint for a new data type in our program.

Generally when we create new class, we need to name it with capital letter.

constructors

constructors will run every time when the new object is created.

private

Only code that is contained inside of the Book class can access attribute or method with private modifier.

getter, setter

We can use getter to get private attribute value.

We can use setter to validate user input value whether comply with a standard.

static

When we create static modifier, we don't need to initialize actual object before using it.

The static attribute setting attribute or method belong to class not object.

class Book
{
    // attribute
    public string title;
    public string author;
    private int pages;
    public static int bookCount = 0;

    // method
    public bool checkBook() 
    {
    }

    public static void BookName(string name)
    {
        Console.WriteLine(name);
    }

    // getter, setter
    public int Pages
    {
        get{ return pages; }
        set{
            if (value > 0 || value < 100)
            {
                this.pages = value;
            } 
        };
    }

    // constructors
    public Book(string title, string author, string pages)
    {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
}

object (actual)

The instance of class.

Each individual objecthave their own attribute value.

Book book1 = new Book();
Console.WriteLine(Book.bookCount)
Book.BookName("123")
#C# Note






你可能感興趣的文章

[ 學習筆記系列 ] 後端基礎 (全) - MySQL 語法、基礎 PHP 與 Session / Cookie

[ 學習筆記系列 ] 後端基礎 (全) - MySQL 語法、基礎 PHP 與 Session / Cookie

Next.js 入門:從 CRA 與 Prerender 進化至 Next.js 的歷程

Next.js 入門:從 CRA 與 Prerender 進化至 Next.js 的歷程

利用後端框架 express 實作抽獎網站的 API

利用後端框架 express 實作抽獎網站的 API






留言討論