oop中的属性可以是字段吗,或者仅仅是setter和getters方法的组合?

时间:2018-06-25 12:10:08

标签: java oop variables properties field

所以我一直在尝试理解属性的确切含义。我已经在stackoverflow和其他网站中搜索了先前要求的Q / A,但是我遇到的答案并不明确是否用setter和getter修改的字段(实例变量)也称为属性。

我遇到的定义是“修改对象字段的setter和getter方法的组合”

下面只是一小段代码,如果您需要更多说明,可以使您更好地理解我的问题。

//property?
String name;

//property?
public void setName(String n){
    name = n;
}
//property?
public String getName(){
    return name;
} 

2 个答案:

答案 0 :(得分:0)

Properties表示属于class的任何成员。它可以是变量,其他/相同类的对象,该类的方法等。

基本上getter/setter仅用于那些成员变量。

局部变量是该方法所属的属性,而不是类的属性。

答案 1 :(得分:0)

在OOP世界中,“财产”的含义很广,其具体含义取决于上下文。通常,它是实体的属性;可能是一个人的名字或年龄,一朵花的颜色,一幢建筑物的高度等。属性具有其名称和值(例如flower.color = red-这里的color是名称,并且red是值),则该值可能属于不同的类型(或类):字符串,数字,人,企业...它可能具有恒定值(在此过程中不会更改)所有者(其所属实体)的生存期),也可以具有可由用户更改的变量值。在软件领域,可以从analisys领域和软件设计的概念层面进行讨论。在这种情况下,人们通常不在乎其实现的准确性。同样,它可以在具体的实现(程序代码)级别使用,然后,实现此概念的方法取决于编程语言。 例如,在Java中,当我们说“属性”时,通常是指一个对象的字段(变量)和几个方法(或用于只读属性的单个方法)来访问其值(getter和设置器):

class Person {
  private String name;         // the field to hold the value
  public Person(String name) { // Constructor
    this.name = name // The name is given at the moment it's been born 
  }
  public String getName() { return Name; } // getter
  // No, name can't be changed after it's been born -- it's a read-only property, thus no setter
  // public void setName(String name) { this.name = name; } // otherwise the setter would look like this
}

在这种情况下,用户可以使用以下代码访问属性的值:

 System.out.println(thisPerson.getName());

其他语言(例如C#)可以用某种更方便的方式对属性进行编码:

class AnotherPersonType {
  private string name // a field to hold the value  
  public string Name 
  {
     get => name;         // getter, the same as "return this.name;" 
     set => name = value; // setter, the same as "this.name = value;"
  }    
}  
.....
anotherPerson.name = "John"; // It looks like an assignment, 
                              // but in fact, the setter is invoked   
相关问题