final 和 static 关键词

final:用来修饰类,成员和局部变量,不能被改变

修饰类:不可以被继承,但可以继承别的类

修饰成员方法:子类不可以重写父类中被final修饰的方法,但可以重写一般方法之后加上final

修饰成员变量:常量,只能赋值一次,可以显性赋值也可以在构造方法中赋值(只有在这两个地方赋值)

修饰局部变量:赋值一次

package com.oracle.Demo01;
//final修饰的类不能被继承但可以继承别的类
public final class Fu extends Fu2 {

}
package com.oracle.Demo01;
//final 修饰的<成员变量>必须在创建对象前赋值  不能为系统内存默认值
public class Fu2 {
    private final int a = 1;
    public final void method(){
        System.out.println("被final修饰的方法");
    }
    public void method2(){
        System.out.println("普通方法");
    }
    
}
package com.oracle.Demo01;

public class Zi extends Fu2{
    public final void method2(){
        System.out.println("这是Zi的普通方法");
    }
}
package com.oracle.Demo01;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Zi z = new Zi();
        z.method();
        z.method2();
    }

}

static:用来修饰类中的变量 在方法和数据共享区的静态区中

被static修饰的成员变量属于类,不属于这个类的对象

被某一个对象修改,其余的都变化

一般用类名.成员变量来调用

main方法是用static修饰的,在main方法中调用方法只能是建立一个对象,用对象调用  或者 把方法用static修饰后直接在里面调用

静态内容(static修饰的内容)存在于静态区中,静态内容是预先于对象存在的(在new对象之前,静态区就已经有静态内容存在了)

静态方法:不能使用this和super,因为它们代表的是本类对象和父类对象,静态内容是在对象之前的

同一类中:静态成员中只能访问静态成员

多态中 成员方法的运行:静态方法看父类,非静态方法看子类重写的方法

定义静态常量的方法:public static final String SCHOOL_NAME = " "  变量名全部大写,多个单词使用下划线连接

package com.oracle.Demo02;

public class Student {
    private String name;
    private int age;
    private static String school;
    public static void eat(){
        System.out.println("吃肉");
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
    
}
package com.oracle.Demo02;

public class Studentson extends Student {
    public static void eat(){
        System.out.println("喝汤");
    }
}
package com.oracle.Demo02;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student stu = new Student();
        stu.setName("zhangsan");
        Student stu1 = new Student();
        stu1.setName("wangwu");
        stu1.setSchool("北京大学");
        System.out.println(stu.getName());
        System.out.println(stu.getSchool());
        System.out.println(stu1.getName());
        System.out.println(stu1.getSchool());
        //多态运行的是父类中的静态方法
        Student stu2 = new Studentson();
        stu2.eat();
    }

}
原文地址:https://www.cnblogs.com/yelena-niu/p/9071118.html