java與.net比較學習系列(7) 屬性


說起屬性,實際上java中沒有屬性這個概念,只有字段和方法,但是可以通過私有字段和聲明get,set方法來實現類似於C#中屬性的效果。

在C#中,聲明屬性有兩種方式,一種是聲明訪問器,另外一種是利用C# 3.0新增的自動屬性。

下面利用代碼來說明:

java中聲明”屬性”:

package property;

/**
 * java中的屬性
 * @author mcgrady
 *
 */
public class Employee {
    //聲明兩個私有字段
    private String name;
    
    private int age;
    
    //分別實現set和get方法
    public void setName(String name)
    {
        this.name= name;
    }
    
    public String getName()
    {
        return this.name;
    }
    
    public void setAge(int age)
    {
        this.age= age;
    }
    
    public int getAge()
    {
        return this.age;
    }
}

C#中聲明屬性:

方式一:聲明訪問器

public class Employee
    {
        private string name;

        private int age;

        //方法一:聲明訪問器
        public string Name
        {
            set { this.name = value; }
            get { return this.name; }
        }

        public int Age
        {
            set { this.age = value; }
            get { return this.age; }
        }
}

方式二:自動屬性

public class Employee
{
        //方法二:自動屬性
        public string Name { get; set; }

        public int Age { get; set; }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM