格式:static{}
①.位置:类里,方法外
②.执行时机:静态代码块也属于静态资源,随着类的加载而加载
优先于对象加载,并且静态资源只会加载一次
③.作用:用于加载那些需要第一时间就加载,并且只加载一次的资源,常用来初始化
package cn.tedu.review;
public class TestBlock {
public static void main(String[] args) {
Person p1 = new Person();
p1.eat();
}
}
class Person{
//构造代码块:类里方法外
{
System.out.println("我是构造代码块");
}
public Person(){
System.out.println("无参构造");
}
public Person(int n){
System.out.println("含参构造");
}
public void eat(){
System.out.println("eat方法");
//局部代码块:方法里
{
System.out.println("我是一个局部代码块");
int i = 100;
System.out.println(i);
}
//System.out.println(i);//不可以使用,因为超出变量i的使用范围
}
}
package cn.tedu.oop;
public class TestBlock {
public static void main(String[] args) {
Apple a1 = new Apple();
Apple a2 = new Apple();
a1.clean();
}
}
//1.创建类
class Apple{
//6.创建本类的静态代码块
static{
System.out.println("我是一个静态代码块");
}
//2.创建本来的构造代码块
{
System.out.println("我是构造代码块");
}
//3.创建本类的无参构造
public Apple(){
System.out.println("我是无参构造");
}
//4.创建本类的普通方法
public void clean(){
System.out.println("我是一个普通方法");
//5.创建本类局部代码块
{
System.out.println("我是局部代码块");
}
}
}
2.静态:
1.static可以修饰属性和方法2.被static修饰的资源成为静态资源
3.静态资源随着类的加载而加载,最先加载,优先于对象进行加载
4.静态资源可以通过类名直接调用
5.静态被全局所有对象共享,值只有一份
6.静态资源只能调用静态资源
7.静态区域内不允许使用this与super关键字 3.final关键字 1.修饰类:最终类,不可以被继承
2.修饰方法:这个方法的最终实现,不可以被重写
3.修饰常量:值不可以被更改,并且定义是必须赋值
package cn.tedu.oop;
public class TestFinal {
}
//1.定义父类
//3.测试类被final修饰
//final class Father2{}
class Father2{
//4.定义父类的普通方法
//public void work(){}
//6.
public void work(){
System.out.println("在工厂里上班");
}
}
//2.定义子类
class Son2 extends Father2{
final int C = 66;
//5.重写父类的方法
@Override//这个注解用来标记这是一个重写的方法
public void work(){
int a = 10;
a= 100;
final int B = 100;
//B = 200;//报错,常量的值不可以被修改
System.out.println("在互联网大厂上班");
System.out.println(Integer.MAX_VALUE);
}
}



