类成员
1.介绍
在java中只能包含成员变量,方法,构造器,初始化块,内部类(接口,枚举)5种成员,其中static可以修饰成员变量,方法,初始化块,内部类(接口,枚举),用static修饰的成员就是类成员。类成员属于整个类,而不属于单独的对象
2.类变量的在内存中的状态
类变量处于整个类,当系统第一次准备使用类时,系统会为该类分配空间,类变量开始生效,直到该类被卸载(生存周期和类一致)
3.用对象可以访问类变量吗?
举个栗子:
public class StaticDemo {
public static void test(){
System.out.println("调用static方法");
}
public static void main(String[]args){
StaticDemo staticDemo=new StaticDemo();
staticDemo.test();//其实是把staticDemo重新变换为类 用类去调用
}
}
答案是可以的,但是其实从表面上而言使用对象去访问,实际上还是委托类去访问类变量
4.static关键字的作用(构建单例类)
单例类:创建的类仅仅只会创建一个实例对象
public class Singleton {
private static Singleton instance;
private Singleton(){}
/**
* 提供静态方法,返回实例
* */
public static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
public class SingletonTest {
public static void main(String[]args){
Singleton s1=Singleton.getInstance();
Singleton s2=Singleton.getInstance();
System.out.println(s1==s2);
//true
}
}
注:类中通用方法toString的使用
重写toString方法可以对对象进行“自我描述”
public class Apple {
private String color;
private String weight;
public Apple(){}
public String getColor() {
return color;
}
public Apple(String color, String weight) {
this.color = color;
this.weight = weight;
}
public void setColor(String color) {
this.color = color;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
//重写方法 toString() 提供描述信息
public String toString(){
return "Apple[color="+color+",weight="+weight+"]";
}
}
通过重写toString方法总是返回该对象所有令人感兴趣的信息组成的字符串
类名【field=值1,field=值2,...】