首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Visual Studio 給 Java 開發者的 C# 指南 (16) - 繼承與衍生類別:語法、單一繼承、介面實作與屬性封裝

     編輯:關於C語言

繼承語法

C# 用冒號 : 同時表示繼承類別與實作介面 (相當於 Java extends/implements)。基類必須在最左邊。

public class ColorPoint : Point, IDrawable { ... }

單一繼承限制

同 Java,C# 類別不支援多重繼承,但可實作多個介面達成同樣目的。

範例:Point 基類與 ColorPoint 衍生類

// 基類:封裝 x, y 座標
public class Point
{
    private int x, y;
    public Point() { x = 0; y = 0; }
    public int X { get => x; set => x = value; }
    public int Y { get => y; set => y = value; }
}

// 衍生類:繼承 Point 並新增顏色
using System.Drawing;
public class ColorPoint : Point
{
    private Color screenColor;
    public ColorPoint() => screenColor = Color.Red;
    public Color ScreenColor { get => screenColor; set => screenColor = value; }
}

關鍵點

  • Point 以 private 欄位 + public 屬性封裝座標。
  • ColorPoint 自動繼承 X/Y 屬性,只需新增 ScreenColor。
  • 屬性 get/set 存取器對應 Java 的 getter/setter,語法更簡潔。
  • 建構子鏈:衍生類建構子隱式呼叫基類無參建構子。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved