public int getMyVariable() { return myVariable; } }
多型/多態(Polymorphism)
重載(Overloading): 相同方法名稱,不同參數
1 2 3 4 5 6 7 8 9
public class MyClass { public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; } }
重寫(Overriding): 子類重寫父類方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public class Animal { public void makeSound() { System.out.println("Some generic sound"); } }
public class Dog extends Animal { @Override public void makeSound() { System.out.println("Bark"); } }
public class Cat extends Animal { @Override public void makeSound() { System.out.println("Meow"); } }
匿名類
簡化代碼
適合只使用一次
範例: OnClickListener, Runnable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
interface Greeting { void greet(); } public class Main { public static void main(String[] args) { Greeting greeting = new Greeting() { @Override public void greet() { System.out.println("Hello, world!"); } }; greeting.greet(); // 输出: Hello, world! } }
訪問局部變量要加final
1 2 3 4 5 6 7 8 9 10 11 12
public class OuterClass { public void someMethod() { final int localVar = 10; // 或者 int localVar = 10;(Java 8及以上版本) Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Local variable value is: " + localVar); } }; new Thread(runnable).start(); } }
// String to array char[] strArray = inputString.toCharArray();
// init int[] array =new int [2]; int[] array =new int [] {0,0}; // 實例 int [] array 與 new int [] {}給初始值 int [] array = new int [] {1, 3, 8, 9, 4, 7, 6}; System.out.println(Arrays.toString(array));
// 也可寫成 int [] array = {1, 3, 8, 9, 4, 7, 6};
// 分割 int [] arr = Arrays.copyOfRange(array, 0, 3); System.out.println(Arrays.toString(arr)); > java -cp /tmp/3QZLh3auEl Main [1, 3, 8]
class Example{ static int data = 0; public Example() {} } class Main { public static void main(String[] argv) { System.out.println(Example.data); // 1 Example exp1 = new Example(); Example exp2 = new Example(); System.out.println(exp1.data); exp2.data = 1; System.out.println(exp2.data); // 2 3 System.out.println(exp1.data); } } > 0 0 1 1
class Example{ final int data = 0; public Example() {} } class Main { public static void main(String[] argv) { System.out.println(Example.data); Example exp1 = new Example(); exp1.data = 1; } } > /tmp/DC9NTE17Mc/Main.java:7: error: non-static variable data cannot be referenced from a static context System.out.println(Example.data); // final static int data = 0;
^ /tmp/DC9NTE17Mc/Main.java:9: error: cannot assign a value to final variable data exp1.data = 1; // final 無法修改。 ^ 2 errors