无参数、无返回值
|
|
Java
123 public void hello() {System.out.print("Hello, World!");}
带参数、无返回值
|
|
Java
123 public void hello(String name){System.out.print("Hello, " + name + "!");}
参数带有默认值
|
|
Java
1234567 public void hello(String name) {if (name == null) {name = "World";}System.out.print("Hello, " + name + "!");}
带返回值
|
|
Java
123 public boolean hasItems() {return true;}
简写
|
|
Java
123 public double cube(double x) {return x * x * x;}
传入数组
|
|
Java
1 public int sum(int... numbers) { }
主函数/Main方法
|
|
Java
123 public class MyClass {public static void main(String[] args){ }}
多个参数
|
|
Java
12345 public static void main(String[]args){openFile("file.txt", true);}public static File openFile(String filename, boolean readOnly) { }
可选参数
|
|
Java
1234567891011121314151617 public static void main(String[]args){createFile("file.txt");createFile("file.txt", true);createFile("file.txt", true, false);createExecutableFile("file.txt");}public static File createFile(String filename) { }public static File createFile(String filename, boolean appendDate) { }public static File createFile(String filename, boolean appendDate, boolean executable) { }public static File createExecutableFile(String filename) { }
泛型
|
|
Java
12345 public void init() {List<String> moduleInferred = createList("net");}public <T> List<T> createList(T item) { }