说起属性,实际上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; } }