属性是定义在类中的,用来描述类实例对象的 数据 或 状态
一、类的语法
[<modifiers>] class < class_name> {
//这个就是属性
[<attribute_declarations>]
[<constructor_declarations>]
[<method_declarations>]
}
二、属性的语法
[<modifiers>] type <attr_name> [=defaultValue];
-
<modifiers>
:属性的访问权限,包括public
private
protected
default
; -
type
:可以是 8 种基本类型,或者(自定义的)引用类型,比如 String; -
<attr_name>
:属性的名字,最好能够直观的表达意思,比如 height,表示身高; -
[=defaultValue]
:默认值,可以有也可以没有;
三、属性的案例
public class Person {
//“人”这个类的属性(数据和状态)
public String name; //名字
private int height; //身高
private int weight; //体重
private Date birthday; //出生日期
}
四、编程实战
代码的详细解读,可以参考视频教程
Person.java
/**
* User: 祁大聪
* 类名必须和文件名一样
*/
public class Person {
//属性
private String name; //名字,系统自动初始化为null
private int age; //年龄,系统自动初始化为0
private int height = 180; //身高,初始化默认值
private int weight = 75; //体重,初始化默认值
public static void main(String[] args) {
Person huGe = new Person(); //创建 huGe这个人(实例)
huGe.name = "胡歌"; //通过点(.)语法给属性赋值
huGe.age = 18;
huGe.height = 175;
System.out.println(huGe.weight); //获取属性的值
}
}