0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

プログラミング練習記録 5日目:C#:クラス・オブジェクト指向・継承

Posted at

1.本日の作業内容

 C# クラス・オブジェクト指向・継承

2.作業目的

 ・復習と使い方の確認。

1.クラスとは?オブジェクト指向とは?

オブジェクト指向の基本

  • クラス:設計図(型)
  • オブジェクト:その実態
  • 目的:データと処理を1つにまとめ、再利用性や保守性を高める

2.基本的なクラスの作成と使い方

  • クラスの定義
public class Person
{
    public string Name;
    public int Age;

    public void SayHello()
    {
        Console.WriteLine($"こんにちは!私は{Name}、{Age}歳です。");
    }
}
  • インスタンス化とメソッド呼び出し
Person person1 = new Person();
person1.Name = "佐藤";
person1.Age = 30;
person1.SayHello();

3.コンストラクタ(初期化)を使う

public class Program
{
    public static void Main()
    {
        Person p = new Person("田中", 28);
        p.SayHello();
    }
}

public class Person
{
    public string Name;
    public int Age;

    // コンストラクタ
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void SayHello()
    {
        Console.WriteLine($"こんにちは、{Name}です。");
    }
}

4.継承とは?

既存のクラス(親クラス)の機能を引き継いで、さらに機能を追加できる仕組み

public class Animal
{
    public void Breathe()
    {
        Console.WriteLine("呼吸している");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("ワンワン!");
    }
}

// 呼び出し
Dog dog = new Dog();
dog.Breathe(); // 親クラスのメソッド
dog.Bark();    // 自分のメソッド

3.まとめ

継承の向きには気を付けないといけないですね。。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?