java 补充(final、static)

final 固定的

final  修饰类的时候,只能作为子类继承,不能作为父类。

final 定义变量时,必须给成员变量赋值。------  1.直接赋值  2.构造方法。

final 修饰成员方法时,该方法不允许被重写。重写父类方法后,可以增加final。

final 修饰局部变量 1.基本数据类型 2.引用数据类型   ;定义时可以不赋值,使用时再赋值,但一次赋值终身不变。

public class Son {
    private final int a;

    public Son() {
        this.a=0;
    }

    public Son(int a) {
        this.a = a;
    }

    public final void eat() {
        System.out.println("eat");
    }
    public void sleep() {
        System.out.println("sleep");
    }
}

 

public class Gson extends Son{
    public final void sleep() {

    }
}

 

public class Demo01 {
    public static void main(String[] args) {
        //final 修饰局部变量 1.基本数据类型 2.引用数据类型
        //定义时可以不赋值,使用时再赋值,但一次赋值终身不变。
        
        final int a;
        a=1;
        final Person p=new Person();//p存的是地址
        p.setName("小红");
        p.setAge(10);
        
    }
}

 

static 静态修饰

被静态修饰的成员变量属于这个类。

访问静态成员变量时,使用:类名.成员名 

同一个类中,静态成员只能访问静态成员,但不可以访问非静态成员;非静态成员可以访问静态成员。

静态成员不能使用 this/super 。

main方法为静态方法仅仅为程序执行入口,它不属于任何一个对象,可以定义在任意类中。

  ------------------   多态调用方法中,编译看=左边,父类有,编译成功,父类没有,编译失败

运行,静态方法,运行父类中的静态方法,

运行,非静态方法,运行子类的重写方法。

成员变量,编译运行全是父类。

public static final double b=3.14;//静态常量

 

public class Student {
    private String name;
    private int age;
    public static String schoolName;//静态修饰:所有对象的共享数据
    public static void eat(){
        System.out.println("eat");
    } 
    public Student() {
        super();
    }
    
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    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 static String getSchoolName() {
        return schoolName;
    }

    public static void setSchoolName(String schoolName) {
        Student.schoolName = schoolName;
    }
    
}

 

public class Demo01 {
    public static void main(String[] args) {
        Student s1=new Student("邢",20);
        Student s2=new Student("刘",18);
        Student.schoolName="北京大学";//改一个所有的都变,全部共享
        System.out.println(s1.getName()+" "+Student.schoolName);
        System.out.println(s2.getName()+" "+Student.schoolName);
     Student.eat(); } }
posted @ 2019-12-20 14:42  墨染千城  阅读(561)  评论(0)    收藏  举报