注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

随机过程

http://superware.blog.163.com

 
 
 

日志

 
 

C# Inheritance  

2014-06-11 20:02:55|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

    One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.

    When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

    The idea of inheritance implements the IS-A relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on. (三段论:哺乳动物是动物,狗是哺乳动物,所以狗是动物)

    单继承实现的是IS-A关系.
    多继承实现的是HAS-A关系.

1.  Base and Derived Classes

    A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.

The syntax used in C# for creating derived classes is as follows:


using System;

namespace ShapeApplication
{
class Shape
{
protected float width;
protected float height;
protected void SetWidth(float w)
{
width = w;
}
protected void SetHeight(float h)
{
height = h;
}
protected float GetWidth()
{
return width;
}
protected float GetHeight()
{
return height;
}
protected float GetArea()
{
return width*height;
}
}

class Rectangle : Shape
{
public void SetRectWidth(float w)
{
SetWidth(w);
}
public void SetRectHeight(float h)
{
SetHeight(h);
}
public float GetRectWidth()
{
return width;
}
public float GetRectHeight()
{
return height;
}
public float GetRectArea()
{
return GetArea();
}
}

class ShapeMain
{
static void Main(string[] args)
{
Rectangle rect = new Rectangle();

rect.SetRectWidth(5);
rect.SetRectHeight(7);

Console.WriteLine("Width = {0}", rect.GetRectWidth());
Console.WriteLine("Height = {0}", rect.GetRectHeight());
Console.WriteLine("Area = {0}", rect.GetRectArea());

Console.WriteLine("");

rect.SetRectWidth(6);
rect.SetRectHeight(8);

Console.WriteLine("Width = {0}", rect.GetRectWidth());
Console.WriteLine("Height = {0}", rect.GetRectHeight());
Console.WriteLine("Area = {0}", rect.GetRectArea());
}
}
}


1、私有成员可以被类自己访问,但不能被任何其他类访问。
2、父类的protected成员可以被子类访问,但子类以外的类不能访问。
3、internal成员可以在本项目中被任何类访问。
4、public成员可在本项目和其他项目中被任何类访问。


注意:对象对类成员的访问与类对成员的访问是一样的,看对象在哪个类中被定义。对象一般在其他类中定义,因此对象对类成员的访问一般属于异地访问。
  评论这张
 
阅读(76)| 评论(0)
推荐

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017