C# 继承类的对象创建
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。
派生类继承基类成员变量和成员方法。因此,必须在创建子类之前创建超类对象。你可以在成员初始化列表中为超类初始化提供指令。
下面你可以看到为继承的类创建的对象。
示例
using System;
namespace Demo {
class Rectangle {
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class Tabletop : Rectangle {
private double cost;
public Tabletop(double l, double w) : base(l, w) { }
public double GetCost() {
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display() {
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Tabletop t = new Tabletop(3, 8);
t.Display();
Console.ReadLine();
}
}
}输出
Length: 3 Width: 8 Area: 24 Cost: 1680
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP