類例題:球繼承圓類(不含屏蔽改寫)

Java:java

class circle
{
    int r;
    float S()
    {
        return 3.14f * r * r;
    }
}
class ball extends circle
{
    float V()
    {
        return 4 / 3f * 3.14f * r * r * r;
    }
}
public class c1
{
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		ball b = new ball();
             b.r = 2;
              System.out.println("球的截面積是:" + b.S() + "球的體積是:" + b.V());
	}
}

  

c#:c#

class circle
    {
        public int r;
        public float S()
        {
            return 3.14f * r * r;
        }
    }
    class ball:circle
    {
        public float V()
        {
            return 4 / 3f * 3.14f * r * r * r;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ball b = new ball();
            b.r = 2;
            Console.WriteLine("球的截面積是:" + b.S() + "球的體積是:" + b.V());
            Console.ReadKey();
        }
    }

  內存示意:blog

相關文章
相關標籤/搜索