注意事項:java
public static void main(String[] args) { final int c = 0; for (int i=0;i<10;i++) { c=i; //錯誤:沒法爲最終變量c分配值 } }
public static void main(String[] args) { for (int i=0;i<10;i++) { final int c = 0; //正確:局部變量,每次循環釋放掉 } }
選其一:jvm
public class Demo { private final String name = "桑鳳嬌";//直接賦值 public Demo(){} } public class Demo2 { private final String name ; public Demo2() { name = "桑鳳嬌";//經過構造方法賦值 } public Demo2(String name) { this.name = name;//經過構造方法賦值 } }
用final修飾的這個類不能有任何子類ide
注意:一個類若是是final修飾的,其中全部的成員方法都沒法進行覆蓋(由於沒有子類)函數
用final修飾的方法不能被覆蓋(不能重寫:override)this
static修飾的內容(隨類的加載而加載,且加載一次;存儲於固定的內存區域(靜態區),因此直接用類名進行調用;優先於對象存在,因此能夠被全部對象共享)spa
修飾成員變量和成員方法,其中被修飾的成員都屬於類,而不是單單屬於某個對象,使用時用類能夠直接調用,而不須要建立對象設計
使用:code
注意:對象
package com.day02; /** * @author SFJ * @date 2019/11/8 * @time 22:19 **/ public class Test1 { private String name="桑鳳嬌"; static String idCard ="3709211998092033**"; public static void method1() { method2();//錯誤,靜態方法不能夠直接訪問非靜態成員方法 new Test1().method2();//正確,靜態方法建立匿名對象訪問非靜態成員方法 System.out.println(name);//錯誤,不能夠直接訪問非靜態成員變量 System.out.println(idCard);//正確,能夠直接訪問靜態成員變量 } public void method2() { System.out.println(idCard);//正確,非靜態方法能夠訪問靜態變量 method1();//正確,非靜態方法能夠訪問靜態方法 } public static void main(String[] args) { Test1 test1 = new Test1(); test1.method2(); } }
靜態代碼塊:繼承
主要做用是給類變量進行初始化賦值
package com.day02; /** * @author SFJ * @date 2019/11/8 * @time 22:53 **/ public class Test3 { private int i=0; Test3(int i) {//第一個構造器:有一個int型形參 this.i = i + 1;//此時this表示引用成員變量i,而非函數參數i System.out.println("Int constructor i——this.i: " + i + "——" + this.i); System.out.println("i-1:" + (i - 1) + "this.i+1:" + (this.i + 1)); //從兩個輸出結果充分證實了i和this.i是不同的! } Test3(String s){ // 第二個構造器:有一個String型形參 System.out.println("String constructor: "+s); } Test3(int i,String s){// 第三個構造器:有一個int型形參和一個String型形參 this(s);//this調用第二個構造器 this.i=i++;//this以引用該類的成員變量 System.out.println("Int constructor: "+i+"/n"+"String constructor: "+s); } public Test3 increment(){//增量 this.i++; return this;//返回的是當前的對象,該對象屬於(Test3) } public static void main(String[] args){ Test3 t0=new Test3(21); Test3 t1=new Test3("桑鳳嬌"); Test3 t2=new Test3(21,"桑鳳嬌"); System.out.println(t1.increment().increment().increment().i); //t0.increment()返回一個在t0基礎上i++的Test3對象, //接着又返回在上面返回的對象基礎上i++的Test3對象! } }
package com.day02; /** * @author SFJ * @date 2019/11/8 * @time 23:08 **/ public class Test4 { public static void main(String[] args) { Son s = new Son(3); System.out.println(); //4 } } class Father { int x = 1; Father() { System.out.println("父類無參的構造方法"); } Father(int x) { this.x = x; System.out.println("父類有參的構造方法"); } void speak() { System.out.println("我是父類"); } } class Son extends Father { int y = 1; Son() { System.out.println("子類無參的構造方法"); } Son(int y) { this.y = y+x; System.out.println("子類帶參的構造方法"); } void run() { super.speak(); //訪問父類的函數 System.out.println("我是子類"); } }