Java 类的属性

Java类的属性

在前一章的示例中,我们称呼类中的x为变量,实际上它是类的一个属性,或者可以说类属性就是类中的变量:

示例

创建MyClass类,它有两个属性:xy:

public class MyClass {
  int x = 5;
  int y = 3;
}

类属性的另一个术语是字段。

访问属性

要访问属性,首先要创建类的对象,然后使用点语法(.)访问。

下面的示例,创建MyClass类的一个对象myObj,打印其属性x

示例

创建一个名为myObj的对象,并打印其属性x的值:

public class MyClass {
  int x = 5;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    System.out.println(myObj.x);
  }
}

修改属性

可以修改属性值:

示例

设置x的值为40:

public class MyClass {
  int x;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    myObj.x = 40;
    System.out.println(myObj.x);
  }
}

或覆盖现有值:

示例

x的值更改为25:

public class MyClass {
  int x = 10;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    myObj.x = 25; // x 现在是 25
    System.out.println(myObj.x); 
  }
}

如果不希望覆盖现有值,可将属性声明为final:

示例

x的值更改为25:

public class MyClass {
  final int x = 10;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    myObj.x = 25; // 将生成一个错误: 无法为 final 变量赋值
    System.out.println(myObj.x); 
  }
}

当希望变量值不变时,如PI(3.14159…),可使用final关键字。

final关键字称为“修饰符”,后续章节将详细介绍。

多个对象

如果创建一个类的多个对象,你可以改变一个对象的属性值,不会影响另一个对象的属性值:

示例

myObj2中的x值更改为25,myObj1中的x不变:

public class MyClass {
  int x = 5;

  public static void main(String[] args) {
    MyClass myObj1 = new MyClass();  // 对象1
    MyClass myObj2 = new MyClass();  // 对象2
    myObj2.x = 25;
    System.out.println(myObj1.x);  // 输出 5
    System.out.println(myObj2.x);  // 输出 25
  }
}

多个属性

类中可以声明任意多的属性:

示例

public class Person {
  String fname = "Kevin";
  String lname = "Wu";
  int age = 35;

  public static void main(String[] args) {
    Person myObj = new Person();
    System.out.println("Name: " + myObj.fname + " " + myObj.lname);
    System.out.println("Age: " + myObj.age);
  }
}
posted @ 2019-10-17 10:58  吴吃辣  阅读(3915)  评论(0编辑  收藏  举报