継承 c# 入門
継承 c# 入門
派生クラスとはもとになる基本クラスを継承したクラスの名前です。
継承の定義
class 派生クラス名 : 基本クラス名{
}
サンプルソース c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Wizard taro = new Wizard();
taro._age = 20;
taro._name = “taro”;
Console.Write(taro._age + taro._name );
taro.spell();
}
class person
{
int age;
string name;
public int _age
{
get
{
return age;
}
set
{
age = value;
}
}
public string _name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class Wizard : person
{
public void spell()
{
Console.Write(“呪文を唱えた”);
}
}
}
}
実行結果は
20taro呪文を唱えた
基本クラスを継承して
派生クラスにspellメソッドを追加しました。
クラスの使い方は基本クラスと同じ感じでクラス名だけ変わってますね。
Wizard taro = new Wizard();
続いてvbですね。
構文
アクセス修飾子 Class 派生クラス名 : Inherits 基本クラス名
End Class
サンプルソース vb
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim taro As New Wizard
taro._age = 20
taro._name = “taro”
Console.Write(taro._age & taro._name)
taro.spellt()
End Sub
Class person
Dim age As Integer
Dim name As String
Public Property _age As Integer
Get
Return age
End Get
Set(ByVal value As Integer)
age = value
End Set
End Property
Public Property _name As String
Get
Return name
End Get
Set(ByVal value As String)
name = value
End Set
End Property
End Class
Public Class Wizard : Inherits person
Sub spellt()
Console.Write(“呪文を唱えた”)
End Sub
End Class
End Class
実行結果は
20taro呪文を唱えた