About some of the content of java class
package ClassLearn;
public class Account {
//成员变量(也叫实例变量)没有static关键字
//堆内存的对象内部中存储,所以访问该数据的时候,必须先创建对象,通过引用的方式访问
String name;
int number;
//封装,只能通过get方法访问,没有static关键字
private int balance;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}//此时的的都是id,不能省略this
/**
* public void setId(int a) {
* id = a; 此时的this可以省略
* }
* 用来区分局部变量和实例变量的时候this不能省略
*/
//成员方法(也叫实例方法)没有static关键字,实例方法访问"引用."来运用
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance; //this关键字是一个引用,保存了内存地址指向自身,this存储在JVM堆内存java对象内部
}
//无参数构造方法,用类名做名字
public Account() {
}
//有参数构造方法,这里的this也不能省略
public Account(String name, int number) {
this.name = name;
this.number = number;
}
//实例方法不要带static,如果这个方法需要对象参加,则不带static,定义为实例方法,用"引用."调用
//以下方法定位实例方法,因为每个账户购物的时候结果是不同的,所以这个动作在完成时必须有对象参与
public void shopping(){
//当张三在购物时,输出张三在购物
//当李四在购物时,输出李四在购物
System.out.println(this.name + "在购物");//this.name name是实例变量必须通过this创建对象来引用访问
//也可以写System.out.println(name + "在购物");
//多数情况下this可以省略
}
//带有static
public static void doSome(){
//执行过程中没有对象,带有static的方法是通过类名直接访问
//上下文中没有对象,就不存在this
//name是一个实例变量,以下代码的含义是访问当前对象的name
//所以这种写法不对 System.out.println(this.name);
}
public static void doOther(){
//假设想访问name这个实例变量
//则要创建对象
Account n = new Account();
//这里访问的name是n引用指向对象的name
System.out.println(n.name);
}
}