Java 基础 22 final和static关键字

2018-02-01  本文已影响3人  小熊先生很不开心

1.1 final关键字的概述及特点

1.1.1 案例代码


package com.itheima;
/*
public final class Father {

}
*/

public class Father {
    public final void method() {
        System.out.println("method father");
    }
}

package com.itheima;

public class Son extends Father {
    public final int age = 20;
    
    public void show() {
        //age = 10;
        System.out.println(age);
    }
    
    /*
    @Override
    public void method() {
        System.out.println("method son");
    }
    */
}

package com.itheima;
/*
 * final:是一个关键字,表示最终的意思。可以用来修饰类,修饰变量,修饰方法。
 * 修饰类:表明该类是最终类,不能被继承
 * 修饰变量:表明该变量是常量,不能再次被赋值
 * 修饰方法:表明该方法是最终方法,不能被重写
 */
public class FinalDemo {
    public static void main(String[] args) {
        Son s = new Son();
        s.show();
    }
}

1.2 static关键字的概述及特点

1.2.1静态的概述

  当在定义类的时候,类中都会有相应的属性和方法。而属性和方法都是通过创建本类对象调用的。当在调用对象的某个方法时,这个方法没有访问到对象的特有数据时,方法创建这个对象有些多余。可是不创建对象,方法又调用不了,这时就会想,那么我们能不能不创建对象,就可以调用方法呢?
可以的,我们可以通过static关键字来实现。static它是静态修饰符,一般用来修饰类中的成员。

1.2.2 静态的特点

1.2.3案例代码


package com.itheima_01;
/*
 * static:是一个关键字,静态的意思。可以用来修饰成员变量和成员方法。
 * static修饰成员的特点:
 *      A:被类的所有对象共享。
 *          其实也是判断一个成员是否应该用static修饰的条件。
 *      B:可以通过类名直接访问
 *      C:优先于对象存在
 *      D:随着类的加载而加载
 */
public class StaticDemo {
    public static void main(String[] args) {
        Student.graduateFrom = "传智学院";
        
        Student s1 = new Student();
        s1.name = "林青霞";
        s1.age = 30;
        //s1.graduateFrom = "传智学院";
        s1.show();
        System.out.println("----------------------");
        
        Student s2 = new Student();
        s2.name = "刘德华";
        s2.age = 28;
        //s2.graduateFrom = "传智学院";
        s2.show();
    }
}

package com.itheima_01;

public class Student {
    public String name;
    public int age;
    //public String graduateFrom; //毕业院校
    public static String graduateFrom; //毕业院校
    
    public void show() {
        System.out.println(name+"---"+age+"---"+graduateFrom);
    }
}

1.3static方法的访问特点及注意事项

1.3.1 案例代码

package com.itheima_02;
/*
 * 非静态的成员方法:
 *      能访问静态的成员变量
 *      能访问非静态的成员变量
 *      能访问静态的成员方法
 *      能访问非静态的成员方法
 * 
 * 静态的成员方法:
 *      能访问静态的成员变量
 *      能访问静态的成员方法
 * 
 * 注意事项:
 *      静态成员方法中不能出现this,super这样的关键字。
 *      原因是:静态是随着类的加载而加载,this,super这样的关键字是随着对象的创建而存在。
 *              先进内存的,不能访问后进内存的。
 */
public class Student {
    //非静态的成员变量
    private String name = "林青霞";
    //静态的成员变量
    private static int age = 30;
    
    //非静态的成员方法
    public void show() {
        this.name = "刘德华";
        System.out.println(name);
        System.out.println(age);
        show2();
        show4();
    }
    
    public void show2() {}
    
    //静态的成员方法
    public static void show3() {
        //this.age
        //this.name
        
        //System.out.println(name);
        System.out.println(age);
        //show2();
        show4();
    }
    
    public static void show4() {}
}
上一篇 下一篇

猜你喜欢

热点阅读