Java面向对象--static

static

static 静态
静态的内容在内存中是保留一份的,并且各个对象之间进行共享
推荐使用类名去访问静态的内容
特点:
    1. 数据共享
    2. 属于类的,并不属于对象
    3. 优先于对象产生的
    
创建对象的过程(简单):
    1. 静态构造器
    2. 通用构造器
    3. 构造方法 --> 创建对象
由于创建对象是在静态内容加载完成之后,在静态方法和静态块里不能使用this
    
静态的东西使用类名去访问   
public class Person {
	String name;
    //静态的内容在内存中是保留一份的,并且各个对象之间进行共享
	static String country = "大清"; // 它是共享的
	String address;
	
	public Person(String name,  String address) {
		this.name = name;
    	// this.country = country;
    	this. address = address;
	}
    public static void main(String[] args) {
        Person p1 = new Person("赵铁柱", "八大胡同"):
        Person p2 = new Person("李小花", "朝阳门");
        
        // 大清完了
        // 不是静态的情况下,有多少人就要改多少次
        // 使用p1.country = "民国", 不推荐这样使用静态变量
        // p1.country = "民国";
     	// 推荐使用类名去访问静态的内容
        Person.country = "民国";
        
        System.out.println(p1.country);
        System.out.println(p2.country);
    }
// 实践知道静态构造器 通用构造器 构造方法的顺序
public class Test {
    String test;
    
    //由于创建对象是在静态内容加载完成之后,在静态方法和静态块里不能使用this
    public static void test() {
        System.out.println(this.test);	// 这里会出错
    }
    
    {
        System.out.println("这里是通用构造器");
    }
    
    static {
        System.out.println("这里是静态构造器");
    }
    
    public Test { 
    	System.out.println("这里是构造方法");
    }
    
    public static void main(String[] args) {
        new Test();
    }
}
// 运行结果
这里是静态构造器
这里是通用构造器
这里是构造方法
pulic class Test1 {
    public static void pen() {
        System.out.println("还我钱");
    }
    
    public static void main(String[] args) {
        pen(); // 在静态方法里调用静态的东西是可以的
        Test1.pen(); // 使用类名去访问静态方法
    }
}

猜你喜欢

转载自www.cnblogs.com/isChenJY/p/12730189.html