继承之隐藏方法、抽象类抽象方法知识点和思考练习

知识点

(五)抽象类和抽象方法

抽象类
在一些情况下,基类只表示一种抽象的概念,只为它的派生类提供公共的界面,却不与具体的事物相联系。为此,C#中引入抽象类的概念,抽象类是指不能被实例化的类,是派生类的基础。通过部分实现或不实现,抽象类可作为派生其他类的模板。用abstract关键字
abstract class 类名 {}

抽象方法
抽象类既可包含非抽象方法,也可包含抽象方法。抽象方法的特征:
1)抽象方法是隐式的虚方法
2)只允许抽象类中声明抽象方法
3)抽象方法声明不提供实际的实现,没有方法体,方法声明以一个封号结束,并且在声明后没有大括号。如:
public abstract void Area();

如果在抽象类中声明了抽象方法,则该抽象类的派生类必须实现基类的抽象方法,否则该派生类不能被实例化。派生类中可以使用override修饰符来实现基类中的抽象方法。

 

思考练习

using System;
namespace Inherit
{
    public class Dimension
    {
        protected double x, y;
        protected const double PI = Math.PI;
        public Dimension(double x1, double y1)
        {
            x = x1;
            y = y1;
        }
        public double Area()
        {
            return x * y;
        }
    }
    public class Sphere : Dimension
    {
        public Sphere(double a, double b) : base(a, b) { }
        new public double Area()
        {
            return PI * x * y;
        }
    }
    public class Program
    {
        static void Main()
        {
            Sphere sphere1 = new Sphere(6, 7);
            Console.WriteLine("The sphere's area is {0}", sphere1.Area());
            Console.ReadLine();
        }

    }
}

using System;
namespace Inherit
{
    public abstract class Dimension
    {
        protected double x, y;
        protected const double PI = Math.PI;
        public Dimension(double x1, double y1)
        {
            x = x1;
            y = y1;
        }
        public abstract double Area();
    }
    public class Sphere : Dimension
    {
        public Sphere(double a, double b) : base(a, b) { }
        public override double Area()
        {
            return PI * x * y;
        }
    }
    public class Program
    {
        static void Main()
        {
            Sphere sphere1 = new Sphere(6, 7);
            Console.WriteLine("The sphere's area is {0}", sphere1.Area());
            Console.ReadLine();
        }

    }
}
posted on 2009-09-24 23:44  友闻语上  阅读(282)  评论(0编辑  收藏  举报