实例变量
也叫对象变量、类成员变量;从属于类由类生成对象时,才分配存储空间,各对象间的实例变量互不干扰,能通过对象的引用来访问实例变量
演示代码
Customer.java
package chapter3.oop08;
/**
* 顾客类
*/
public class Customer {
/**
* 姓名
*/
private String name; //属性:实例变量
/**
* 生日
*/
private String birthday;
/**
* 性别
*/
private boolean gender;
/**
* 联系电话
*/
private String tel;
/**
* 实例方法(因为没有加static)
* 这种行为动作是需要对象才能触发的。
* 需要对象才能参与的
*/
public void shopping(){
//this. 大部分情况下是可以省略的
System.out.println(this.name + "XXX正在疯狂购物!!!");
//最后要结账
//this.pay();
//this. 大部分跟情况下是可以省略的
pay();
}
//以下程序报错的原因是什么呢?(static关键字再讲)
/*
public static void test(){
System.out.println(this.name + "正在疯狂购物!!!");
this.pay();
System.out.println(name + "正在疯狂购物");
pay();
}
*/
public void pay(){
System.out.println(this.name + "XXX正在付款...");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
CustomerTest.java
package chapter3.oop08;
public class CustomerTest {
public static void main(String[] args) {
//创建顾客对象
Customer momo = new Customer();
//给属性赋值
momo.setName("漠漠");
momo.setBirthday("2001-2-2");
momo.setGender(true);
momo.setTel("19913211869");
//购物
//实例对象的调用语法 : “引用.”
momo.shopping();
}
}