一、final关键字
1.被final关键字修饰的类不能被继承
例:public final
class F{
}
public class S extends F{
}
public class Test{
public static void main(String[] args){
S stu = new S();
}
}
程序会报错,编译不通过。
2.被final修饰的方法不可以被重写但可以被重载
例:public class Teacher{
public fianl void teach(){
System.out.println("调用了teach方法");
}
public void teach(String zhang){
System.out.println("zhang"+"调用了teach方法");//允许被重载
}
}
public class Student extends Teacher{
public void teach(){
System.out.println("s调用了teach方法");
}
}
public class Test{
public static void main(String[] args){
Student stu = new Student();
stu.teach();
}
}
结果是编译不通过。
3.被final修饰的成员变量或局部变量是常量,是个固定不变的值,而且在定义变量的时候需要初始化。
例:
public final class Person{
public final int a = 10;
a = 5;//a是被final修饰的变量变成了一个常量10,不能再次被赋值 。
}
4.被final修饰的引用类型的变量为对象的地址,地址值不可以被修改,但是对象的属性值可以修改。
例:
public class Food{
public int a = 10;
}
public class Test{
public static void main(String[] args){
final Food f = new Food();
f = new Food();//对象f被final修饰了,地址值唯一不会变更,所以报错
f.a= 5;//允许修改f里面的属性值
}
}
二、static关键字
1. 用static修饰的成员变量和方法属于类,类中所有实例化对象共享这个被修饰的变量和方法。调用方法:类名.成员变量(方法名)
例:public class Student{
public static String schoolName;
}
public class Test{
public static void main(String[] args){
Student stu1 = new Student();
Student stu2 =new Student();
Student.schoolName = "南华大学";
System.out.println(stu1+"=="+stu1.schoolName);
System.out.println(stu2+"=="+stu2.schoolName);
}
}
输出的结果为:stu1==南华大学
stu2==南华大学
2.static修饰的属性和方法是在类加载时产生的,也叫静态的属性和方法。非静态的属性和方法是在new对象的时候被分配到一个个堆内存中的。
3.被static修饰的代码块为静态代码块,类的静态代码块最优先调用,而且只会调用一次
例:public class Feather{
{
System.out.println("执行了父类的普通代码块");
}
{
public Feather(){
System.out.println("执行了父类的构造方法");
}
}
{
static{
System.out.println("执行了父类静态代码块");
}
}
}
public class Son extends Feather{
{
System.out.println("执行了子类的普通代码块");
}
{
public Son(){
System.out.println("执行了子类的构造方法");
}
}
{
static{
System.out.println("执行了子类静态代码块");
}
}
}
打印结果:执行了父类静态代码块
执行了子类静态代码块
执行了父类普通代码块
执行了父类构造方法
执行了子类普通代码块
执行了子类构造方法