person類與其子類在使用中的內存狀況(含java的改寫和c#的屏蔽)

JAVA 普通person類及調用代碼:java

public class Person
{
	public String xm;
	public int nl;
	public void setme(String x,int y)
	{
		xm=x;
		nl=y;
	}
	public void showme()
	{
		System.out.println("我是"+xm+",今年"+nl+"歲");
	}
}
public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		Person a,b;
		a=new Person();
		b=new Person();
		a.setme("張三",20);
		b.setme("李四",18);
		a.showme();
		b.showme();
	}

C# 普通person類及調用代碼:spa

class Person
    {
        public String xm;
        public int nl;
        public void setme(String x, int y)
        {
            xm = x;
            nl = y;
        }
        public void showme()
        {
            Console.WriteLine("我是" + xm + ",今年" + nl + "歲");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person a, b;
            a = new Person();
            b = new Person();
            a.setme("張三", 20);
            b.setme("李四", 18);
            a.showme();
            b.showme();
            Console.ReadKey();
        }
    }

  對應內存示意圖(不嚴謹,僅爲說明問題,下同)blog

JAVA person類的子類person1及調用代碼:內存

public class Person1 extends Person
{
	public void showme()
	{
		System.out.println("我是中國人"+xm+",今年"+nl+"歲");
	}
}

public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		Person1 a;
		Person b,c;
		a=new Person1();
		b=new Person();
		a.setme("張三",20);
		b.setme("李四",18);
		c=a;
		a.showme();
		b.showme();
		c.showme();
	}

對應內存示意圖:string

運行結果:it

C# person類的子類person1及調用代碼: class

class Person1 : Person
    {

        new public void showme()//沒有new會報一個警告錯誤,不影響運行結果。之後會講到。
        {
            Console.WriteLine("我是中國人" + xm + ",今年" + nl + "歲");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person1 a;
            Person b,c;
            a = new Person1();
            b = new Person();
            a.setme("張三", 20);
            b.setme("李四", 18);
            c = a;
            a.showme();
            b.showme();
            c.showme();
            Console.ReadKey();
        }
    }

  對應內存示意圖:im

運行結果:static

相關文章
相關標籤/搜索