Java local class(局部類)規則: local class的一些定義規則:html
一、在local class中不能定義static的方法或者變量,可是能夠定義常量 static final修飾。java
二、在local class中不能定義接口。oracle
三、local class中訪問的外部變量必須是final類型修飾的。code
四、local class通常用於特定的結構。orm
參考官方教程htm
package inner; public class LocalClassExample { static String regularExpression = "[^0-9]"; public static void validatePhoneNumber(String phoneNumber1, String phoneNumber2) { //JDK 7及其之前,局部類訪問成員變量只能是final類型,若是不是final類型的會報錯。 final int numberLength = 10; // Valid in JDK 8 and later: // int numberLength = 10; //用於判斷電話號碼格式的局部類 class PhoneNumber { String formattedPhoneNumber = null; PhoneNumber(String phoneNumber){ // numberLength = 7; String currentNumber = phoneNumber.replaceAll( regularExpression, ""); if (currentNumber.length() == numberLength) formattedPhoneNumber = currentNumber; else formattedPhoneNumber = null; } public String getNumber() { return formattedPhoneNumber; } // Valid in JDK 8 and later: // public void printOriginalNumbers() { // System.out.println("Original numbers are " + phoneNumber1 + // " and " + phoneNumber2); // } } PhoneNumber myNumber1 = new PhoneNumber(phoneNumber1); PhoneNumber myNumber2 = new PhoneNumber(phoneNumber2); // Valid in JDK 8 and later: // myNumber1.printOriginalNumbers(); if (myNumber1.getNumber() == null) System.out.println("First number is invalid"); else System.out.println("First number is " + myNumber1.getNumber()); if (myNumber2.getNumber() == null) System.out.println("Second number is invalid"); else System.out.println("Second number is " + myNumber2.getNumber()); } //局部類中能夠定義常量,可是不可以定義靜態方法和靜態變量 public void sayGoodbyeInEnglish() { class EnglishGoodbye { public static final String farewell = "Bye bye"; public void sayGoodbye() { System.out.println(farewell); } } EnglishGoodbye myEnglishGoodbye = new EnglishGoodbye(); myEnglishGoodbye.sayGoodbye(); } //局部類中不能定義接口 如下定義是錯誤的 public void greetInEnglish() { interface HelloThere { public void greet(); } class EnglishHelloThere implements HelloThere { public void greet() { System.out.println("Hello " + name); } } HelloThere myGreeting = new EnglishHelloThere(); myGreeting.greet(); } public static void main(String... args) { validatePhoneNumber("123-456-7890", "456-7890"); } }