static关键字

static关键字可以修饰属性、方法、游离块、内部类。分别称为静态属性、静态方法、静态游离块和内部类。

没有static修饰的属性,对象和对象之间的属性是不共享的。 类中的属性和方法都是对 对象的描述 ,而有些属性和 方法是修饰类的,例如人类的人口数量、人类的起源、人类的文明 ,这些属性和方法就可以用static修饰。

确切的理解:static修饰的属性,对象和对象之间是共享的。

public class Person {
    String name;
    //人口总数 显示内存中的人口总数
    static int count ;
    public Person() {
    count++;
    }
}

    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Person();
        //count属性,对象和对象之间是可以共享的
        System.out.println(p1.count);
        System.out.println(p2.count);
    }

由于静态的属性和方法不是修饰对象的,而是修饰类的,因此调用静态的属性和方法可以使用类名调用

public static void main(String[] args) {
    Person p1 = new Person();
    Person p2 = new Person();
    //类名为Person,用类名调用
    System.out.println(Person.count);
}
//静态方法
public static void civilization() {
    System.out.println("人类的文明发展");
}
public static void main(String[] args) {
    Person p1 = new Person();
    Person p2 = new Person();
    System.out.println(Person.count);
    Person.civilization();
}

静态方法中不能使用this关键字,不能调用非静态的属性和方法

 static和private修饰的方法不能被重写

public static void main(String[] args) {
    Person.method();
    Animal.method();
    Person p = new Person();
    p.method();
    Animal a = new Person();
    //静态方法和对象无关的 ,和类相关
    //a是Animal类型 , a.method() 是Animal.method();
    a.method();
}

游离块

又叫初始化块、构造块, 可以写在类中

当调用构造器时,执行游离块,先执行游离块,再执行构造器代码,当发现每个构造器都要执行一段代码,写在游 离块中

游离块的执行顺序:先父类游离块、父类构造器、子类游离块、子类构造器

静态游离块

在游离块的前面加 static修饰 ,静态游离块在类被加载时执行,静态游离块只执行一次

静态游离块、游离块、构造器的执行顺序:父类静态游离块、子类静态游离块、父类游离块、父类构造器、子类游 离块、子类构造器

public class Test {
    static {
    System.out.println("执行静态游离块");
    }
    String name;
    public void method() {
    }
    public static void method2() {
    }
    public static void main(String[] aa) {
        //仅仅是声明,不加载Test类
        //JVM 执行了 Test.main()
        //加载了Test类
        //Test t ;
        //method(); //错误 可以是 Test t = new Test() ; t.method(); //正确
        method2();
    }
}

例:

/*Person 类*/
public class Person {
	static {
		System.out.println("Person的静态块");
	}
	{
		System.out.println("Person类的匿名块");
	}
	public Person() {
		System.out.println("Person的构造方法");
	}
}

/*Student 类*/
public class Student extends Person {
	static{
		System.out.println("Student 静态块");
	}
	
	{
		System.out.println("Student匿名块");
	}
	
	public Student() {
		System.out.println("Student的构造方法");
	}
}
/* 测试类*/
public class Test {
	public static void main(String[] args) {	
		new Student();
	}
}

 执行结果 :

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aigo-2021

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值