C#继承2
基类和派生类
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。
C# 中创建派生类的语法如下:
<访问修饰符符> class <基类>
{
...
}
class <派生类> : <基类>
{
...
}
假设,有一个基类 Shape,它的派生类是 Rectangle:
实例
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// 派生类
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// 打印对象的面积
Console.WriteLine("总面积: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:
总面积: 35
基类和派生类
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。
C# 中创建派生类的语法如下:
<访问修饰符符> class <基类>
{
...
}
class <派生类> : <基类>
{
...
}
假设,有一个基类 Shape,它的派生类是 Rectangle:
实例
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// 派生类
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// 打印对象的面积
Console.WriteLine("总面积: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:
总面积: 35
全部评论
相关推荐
07-17 12:09
门头沟学院 Java 点赞 评论 收藏
分享

点赞 评论 收藏
分享