手册
目录
前言:
在本教程中,您将学习如何使用Java类属性,Java类属性在上一章中,我们在示例中使用了x的术语变量(如下所示)。它实际上是类的一个属性。
在上一章中,我们在示例中使用了x的术语"变量"(如下所示)。它实际上是类的一个属性。或者可以说类属性是类中的变量:
创建一个名为"MyClass"的类,该类具有两个属性:x 和 y:
public class MyClass {
int x = 5;
int y = 3;
}
类属性的另一个术语是字段。
您可以通过创建类的对象和使用点语法(.)来访问属性:
下面的示例将创建MyClass类的对象,名称为myObj。我们使用对象上的x属性打印其值:
Create an object called "myObj" and print the value of 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:
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 关键字称为"修饰符"。在Java修饰符一章中,您将了解有关这些的更多信息。
如果创建一个类的多个对象,可以在更改一个对象中的属性值时,而不会影响另一个对象中的属性值:
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
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 = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args) {
Person myObj = new Person();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
点击 "运行实例" 按钮查看在线实例
下一章将教您如何创建类方法以及如何使用对象访问它们。
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.2万人学习
共49课时
77万人学习
共29课时
61.7万人学习
共25课时
39.3万人学习
共43课时
70.9万人学习
共25课时
61.6万人学习
共22课时
23万人学习
共28课时
33.9万人学习
共89课时
125万人学习