C#类的(封装,继承,多态)

1.封装,隐藏细节,暴露接口

public class Person  
{  
    private string name;  
    private int age;  
  
    public Person(string name, int age)  
    {  
        this.name = name;  
        this.age = age;  
    }  
  
    public string GetName()  
    {  
        return this.name;  
    }  
  
    public int GetAge()  
    {  
        return this.age;  
    }  
  
    public void SetName(string name)  
    {  
        this.name = name;  
    }  
  
    public void SetAge(int age)  
    {  
        this.age = age;  
    }  
}

2.继承

继承是指定义一个新类时,可以从已有的类派生而来,继承已有的类的属性和方法,同时可以添加新的属性和方法。

public class Animal : Mammal  
{  
    public void MakeSound()  
    {  
        Console.WriteLine("The animal makes a sound");  
    }  
}  
  
public class Mammal : Vertebrate  
{  
    public void GivesBirth()  
    {  
        Console.WriteLine("The mammal gives birth");  
    }  
}  
  
public class Vertebrate  
{  
    public void HasBackbone()  
    {  
        Console.WriteLine("The vertebrate has a backbone");  
    }  
}

Animal类继承了Mammal类,Mammal类继承了Vertebrate类。

通过继承,我们可以避免重复编写已有的代码,并且可以扩展已有的功能。

在上面的示例中,Animal类可以访问Mammal类和Vertebrate类的所有方法,同时添加了新的MakeSound方法。

3.多态

多态是指一个接口或超类可以引用多种类型的对象,并且可以根据实际对象的类型调用相应的方法。

//这是一个接口,名为 Shape,它有一个方法 Area(),这个方法返回一个 double 类型的值。

这个方法的设计意味着任何实现这个接口的类都需要提供计算其面积的方法。

interface Shape  
{  
    double Area();  
}  
  

//一个名为 Circle 的类,它实现了 Shape 接口。

它有一个私有字段 radius 和一个构造函数,该构造函数接受一个 double 类型的参数并将其设置为 radius 字段的值。

此外,它还实现了 Area() 方法,用于计算圆的面积。

class Circle : Shape  
{  
    private double radius;  
  
    public Circle(double radius)  
    {  
        this.radius = radius;  
    }  
  
    public double Area()  
    {  
        return Math.PI * radius * radius;  
    }  
}  
  

//一个名为 Rectangle 的类,它也实现了 Shape 接口。

它有两个私有字段:width 和 height,以及一个构造函数,该构造函数接受两个 double 类型的参数并将它们分别设置为 width 和 height 字段的值。

此外,它也实现了 Area() 方法,用于计算矩形的面积。

class Rectangle : Shape  
{  
    private double width;  
    private double height;  
  
    public Rectangle(double width, double height)  
    {  
        this.width = width;  
        this.height = height;  
    }  
  
    public double Area()  
    {  
        return width * height;  
    }  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值