C#面向对象基础(六) 继承

本文详细阐述了C#中继承的概念,通过实例展示了如何在类Animal的基础上派生出狼类Wolf和山羊类Goat,同时介绍了访问控制修饰符、密封类以及构造方法的应用。此外,还探讨了继承带来的好处及潜在的设计问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承 

描述的是 is a kind of 的关系.

比如:Animal类  wolf类.  Wolf类是Animal类的子类,Animal类是父类.Wolf类从Animal类派生,Wolf类继承了Animal类

Wolf是一种Animal. 

失败的设计:

 

 1  public class Wolf
 2     {
 3         public string name;
 4         public int age;
 5         public bool ishungry;
 6         private int weight;
 7         public void Sleep()
 8         {
 9             Console.WriteLine("睡觉..."); 
10         }
11         public void Eat()
12         {
13             Console.WriteLine("吃羊...");
14         }
15     }
16     public class Goat 
17     {
18         public string name;
19         public int age;
20         public bool ishungry;
21         private int weight;
22         public void Sleep()
23         {
24             Console.WriteLine("睡觉..."); 
25         }
26         public void Eat()
27         {
28             Console.WriteLine("吃草...");
29         }
30     }

 

用到了继承很好的设计!

 

class Animal
    {
        
public string name;
        
public int age;
        
public bool ishungry;
        
private int weight;
        
public void Sleep()
        {
            Console.WriteLine(
"睡觉..."); 
        }
    }
    
public class Wolf : Animal
    {
        
public void Eat()
        {
            Console.WriteLine(
"吃羊...");
        }
    }
    
public class Goat : Animal
    {
        
public void Eat()
        {
            Console.WriteLine(
"吃草...");
        }
    }

访问控制修饰符

public 公开的,谁想访问都可以.

private 私有的,类内部访问

proteced  受保护的,子类可以访问.

默认private

 

密封类

sealed!

 

 

 public class Animal
    {
        
public string name;
        
public int age;
        
public bool ishungry;
        
protected int weight;
      
        
public Animal(string n,int a)
        {
            name 
= n;
            age 
= a;
            Console.WriteLine(
"Animal构造方法"); 
        }
        
public void Sleep()
        {
            Console.WriteLine(
"睡觉...");            
        }
    }
    
public class Wolf : Animal
    {
        
public Wolf():base("noname",1)
        { }
        
public Wolf(string n):base(n,1)
        { 
        }
        
public Wolf(string n, int a):base(n,a)
        {
            Console.WriteLine(
"Wolf构造方法");
        }
        
public new void Sleep()
        {
            Console.WriteLine(
"Wolf睡觉...");  
        }
        
public void Eat()
        {
            Console.WriteLine(
"吃羊...");
            
base.Sleep();
        }
    }

 

转载于:https://www.cnblogs.com/imxh/archive/2011/09/08/2171506.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值