类与对象

  1. public class Demo {
  2. public static void main(String[] args) {
  3. // 创建person对象
  4. Person person = new Person();
  5. person.name = "张三";
  6. person.age = 18;
  7. person.tell();
  8. }
  9. }
  10. // 定义Person类
  11. class Person {
  12. String name;
  13. int age;
  14. public void tell() {
  15. System.out.println("姓名:" + name + ",年龄:" + age);
  16. }
  17. }

内存分析

Person person = new Person();

栈内存 堆内存
person name:null
age:0

person.name = "张三";
person.age = 18;

栈内存 堆内存
person name:张三
age:18

成员属性封装

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Person person = new Person();
  4. person.setName("张三");
  5. person.setAge(-5);
  6. System.out.println(person.getName());
  7. System.out.println(person.getAge());
  8. }
  9. }
  10. class Person {
  11. private String name;
  12. private int age;
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name2) {
  17. name = name2;
  18. }
  19. public int getAge() {
  20. return age;
  21. }
  22. public void setAge(int age2) {
  23. if(age2 < 0) {
  24. age = 1;
  25. }else {
  26. age = age2;
  27. }
  28. }
  29. }

构造方法和匿名对象

如果我们手动在某个类中定义了一个有参数的构造函数,那么这个默认的无参构造函数就不会自动添加了。需要手动创建!
成员变量的默认值,如int -> 0,Integer -> null

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Person person1 = new Person();
  4. person1.tell();
  5. Person person2 = new Person("张三", 18);
  6. person2.tell();
  7. // 匿名对象
  8. new Person("李四",19).tell();
  9. }
  10. }
  11. class Person {
  12. String name;
  13. int age;
  14. // 构造方法1
  15. public Person() {
  16. }
  17. // 构造方法2
  18. public Person(String name2, int age2) {
  19. name = name2;
  20. age = age2;
  21. }
  22. // 普通方法
  23. public void tell() {
  24. System.out.println("姓名:" + name + ",年龄:" + age);
  25. }
  26. }

Java中只有值传递

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. Person person = new Person();
  4. person.setName("张三");
  5. fun(person);
  6. System.out.println(person.getName());
  7. }
  8. public static void fun(Person person) {
  9. person = new Person();
  10. person.setName("李四");
  11. }
  12. }
  13. class Person {
  14. private String name;
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. }

this的使用

  1. public class Demo {
  2. public static void main(String[] args) {
  3. new Person().tell();
  4. new Person("张三").tell();
  5. new Person("李四",19).tell();
  6. }
  7. }
  8. class Person {
  9. // 属性
  10. private String name;
  11. private int age;
  12. // 构造方法
  13. public Person() {
  14. this("无名");
  15. }
  16. public Person(String name) {
  17. this(name, 1);
  18. }
  19. public Person(String name, int age) {
  20. this.name = name;
  21. this.age = age;
  22. }
  23. // get set 方法
  24. public String getName() {
  25. return name;
  26. }
  27. public void setName(String name) {
  28. this.name = name;
  29. }
  30. public int getAge() {
  31. return age;
  32. }
  33. public void setAge(int age) {
  34. this.age = age;
  35. }
  36. // 普通方法
  37. public void tell() {
  38. System.out.println("姓名:" + this.name + ",年龄:" + this.age);
  39. }
  40. }

static关键字

Java中共有三种变量,分别是类变量、成员变量和局部变量。他们分别存放在JVM的方法区、堆内存和栈内存中

static属性

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println(Person.country);
  4. new Person("张三", 18).tell();
  5. new Person("李四",19).tell();
  6. }
  7. }
  8. class Person {
  9. static String country = "中国";
  10. String name;
  11. int age;
  12. public Person(String name, int age) {
  13. this.name = name;
  14. this.age = age;
  15. }
  16. public void tell() {
  17. System.out.println("姓名:" + name + ",年龄:" + age + ",国籍:" + country);
  18. }
  19. }

static方法

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println(MyUtil.max(3, 4));
  4. }
  5. }
  6. class MyUtil {
  7. public static int max(int x, int y) {
  8. return x>y ? x : y;
  9. }
  10. }

代码块

普通代码块

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("普通代码块");
  4. {
  5. String name = "张三";
  6. System.out.println(name);
  7. }
  8. {
  9. String name = "张三";
  10. System.out.println(name);
  11. }
  12. System.out.println("普通代码块");
  13. }
  14. }

构造代码块

  1. public class Demo {
  2. public static void main(String[] args) {
  3. new Person();
  4. new Person();
  5. new Person();
  6. }
  7. }
  8. class Person {
  9. public Person() {
  10. System.out.println("实例化对象");
  11. }
  12. {
  13. System.out.println("构造代码块,每次实例化对象前执行");
  14. }
  15. }

静态代码块

  1. public class Demo {
  2. static {
  3. System.out.println("程序初始化");
  4. }
  5. public static void main(String[] args) {
  6. new Person();
  7. new Person();
  8. new Person();
  9. }
  10. }
  11. class Person {
  12. public Person() {
  13. System.out.println("实例化对象");
  14. }
  15. static {
  16. System.out.println("静态代码块");
  17. }
  18. {
  19. System.out.println("构造代码块,每次实例化对象前执行");
  20. }
  21. }

数组

int数组

  1. public class Demo {
  2. public static void main(String[] args) {
  3. int[] arr1 = {2,7,3,9,4};
  4. int[] arr2 = new int[3];
  5. arr2[0] = 11;
  6. arr2[1] = 22;
  7. arr2[2] = 33;
  8. printArr(arr1);
  9. printArr(arr2);
  10. }
  11. public static void printArr(int[] arr) {
  12. for(int i=0; i<arr.length; i++) {
  13. System.out.println(arr[i]);
  14. }
  15. }
  16. }

foreach

  1. public class Demo {
  2. public static void main(String[] args) {
  3. int[] arr = {2,7,3,9,4};
  4. for (int num : arr) {
  5. System.out.println(num);
  6. }
  7. }
  8. }

多维数组

  1. public class Demo {
  2. public static void main(String[] args) {
  3. int[][] arr = {{1,2,3},{4,5,6},{7,8,9,0}};
  4. for (int[] temp : arr) {
  5. for (int num : temp) {
  6. System.out.print(num + "、");
  7. }
  8. System.out.println();
  9. }
  10. }
  11. }

排序

  1. public class Demo {
  2. public static void main(String[] args) {
  3. int[] arr = { 2, 7, 3, 9, 4 };
  4. // 排序
  5. for (int i = 0; i < arr.length - 1; i++) {
  6. for (int j = 0; j < arr.length - 1 - i; j++) {
  7. if (arr[j] > arr[j + 1]) {
  8. int temp = arr[j];
  9. arr[j] = arr[j + 1];
  10. arr[j + 1] = temp;
  11. }
  12. }
  13. }
  14. // 输出
  15. for (int num : arr) {
  16. System.out.print(num + "、");
  17. }
  18. }
  19. }

排序(Java提供的排序方法)

  1. public class Demo {
  2. public static void main(String[] args) {
  3. int[] arr = { 2, 7, 3, 9, 4 };
  4. java.util.Arrays.sort(arr);
  5. String result = java.util.Arrays.toString(arr);
  6. System.out.println(result);
  7. }
  8. }

可变参数

  1. public class Demo {
  2. public static void main(String[] args) {
  3. fun(1);
  4. fun(1,2);
  5. fun(1,2,3);
  6. }
  7. public static void fun(int... arr) {
  8. for(int num : arr) {
  9. System.out.print(num + "、");
  10. }
  11. System.out.println();
  12. }
  13. }

对象数组

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Person[] persons = new Person[2];
  4. persons[0] = new Person("张三", 18);
  5. persons[1] = new Person("李四", 19);
  6. for (Person person : persons) {
  7. System.out.println(person.getInfo());
  8. }
  9. }
  10. }
  11. class Person {
  12. private String name;
  13. private int age;
  14. public Person(String name, int age) {
  15. this.name = name;
  16. this.age = age;
  17. }
  18. public String getInfo() {
  19. return "姓名:" + name + ", 年龄:" + age;
  20. }
  21. }

类关联结构

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Person person = new Person("张三", 18);
  4. Car car = new Car("宝马", 500000.00);
  5. person.setCar(car);
  6. car.setPerson(person);
  7. System.out.println(person.getCar().getInfo());
  8. System.out.println(car.getPerson().getInfo());
  9. }
  10. }
  11. class Person {
  12. private String name;
  13. private int age;
  14. private Car car;
  15. public Car getCar() {
  16. return car;
  17. }
  18. public void setCar(Car car) {
  19. this.car = car;
  20. }
  21. public Person(String name, int age) {
  22. this.name = name;
  23. this.age = age;
  24. }
  25. public String getInfo() {
  26. return "姓名:" + name + ", 年龄:" + age;
  27. }
  28. }
  29. class Car {
  30. private String name;
  31. private double price;
  32. private Person person;
  33. public Person getPerson() {
  34. return person;
  35. }
  36. public void setPerson(Person person) {
  37. this.person = person;
  38. }
  39. public Car(String name, double price) {
  40. this.name = name;
  41. this.price = price;
  42. }
  43. public String getInfo() {
  44. return "车名:" + name + ", 价格:" + price;
  45. }
  46. }

字符串

字符串比较

  1. public class Demo {
  2. public static void main(String[] args) {
  3. String str1 = new String("AAA");
  4. String str2 = new String("AAA");
  5. String str3 = "AAA";
  6. System.out.println(str1 == str2);
  7. System.out.println(str2 == str3);
  8. System.out.println(str1.equals(str2));
  9. System.out.println(str2.equals(str3));
  10. }
  11. }

字符串手工入池

  1. public class Demo {
  2. public static void main(String[] args) {
  3. String str1 = "AAA";
  4. String str2 = new String("AAA").intern();
  5. System.out.println(str1 == str2);
  6. }
  7. }

字符串常量池

  • String s = "a" + "b";,编译器会进行常量折叠,即变成 String s = "ab"
  • 对于能够进行优化的String s = "a" + xxx;StringBuilderappend()方法替代,最后调用toString()方法
    1. public class Demo {
    2. public static void main(String[] args) {
    3. {
    4. String str1 = "AAA";
    5. String str2 = "AA" + "A";
    6. System.out.println(str1 == str2);
    7. }
    8. {
    9. String str = "A";
    10. String str1 = "AAA";
    11. String str2 = "AA" + str;
    12. System.out.println(str1 == str2);
    13. }
    14. }
    15. }

    主方法传参

    1. public class Demo {
    2. public static void main(String[] args) {
    3. for (String string : args) {
    4. System.out.println(string);
    5. }
    6. }
    7. }
    编译代码:javac Demo.java
    运行程序:java Demo aaa bbb "cccc ddd"

    字符串常用方法

    ```java import java.util.Arrays;

public class Demo { public static void main(String[] args) { String str1 = “hello world”; String str2 = “hello world”; System.out.println(str1.equals(str2));// 是否相等 System.out.println(str1.equalsIgnoreCase(str2));// 是否相等(忽略大小写) System.out.println(str1.compareTo(str2));// 比较大小 System.out.println(str1.compareToIgnoreCase(str2));// 比较大小(忽略大小写) System.out.println(str1.startsWith(“hello”));// 是否以hello开头 System.out.println(str1.endsWith(“hello”));// 是否以hello结尾 System.out.println(str1.contains(“hello”));// 是否包含hello System.out.println(str1.replace(“ “, “-“));// 字符串替换 System.out.println(Arrays.toString(str1.split(“ “)));// 字符串拆分 System.out.println(str1.substring(2, 10));// 字符串截取 System.out.println(str1.substring(6));// 字符串截取 System.out.println(str1.substring(str1.indexOf(“ “)+1));// 字符串截取 System.out.println(String.format(“姓名:%s,年龄:%d,成绩:%5.2f”, “张三”,18,89.123456));// 字符串格式化 System.out.println(str1.charAt(0));// 获取指定位置的字符 System.out.println(str1.isEmpty());// 是否是空字符串 System.out.println(str1.concat(str2));// 字符串拼接 System.out.println(str1.length());// 字符串长度 System.out.println(“ AAA BBB “.trim());// 去除首尾空格 System.out.println(str1.toUpperCase());// 转大写 System.out.println(str1.toCharArray());// 转小写 } }

  1. <a name="IRs3L"></a>
  2. ### 数字转字符串
  3. - 第三行和第四行没有任何区别,因为`String.valueOf(i)`也是调用`Integer.toString(i)`来实现的
  4. - 第二行代码其实是`String i1 = (new StringBuilder()).append(i).toString();`,首先创建一个`StringBuilder`对象,然后再调用`append`方法,再调用`toString`方法

int i = 5; String i1 = “” + i; String i2 = String.valueOf(i); String i3 = Integer.toString(i);

  1. <a name="zfbBi"></a>
  2. ### String的长度限制
  3. - 字符串有长度限制,在编译期,要求字符串常量池中的常量不能超过65535,并且在javac执行过程中控制了最大值为65534
  4. - 在运行期,长度不能超过Int的范围,否则会抛异常
  5. <a name="EdvDe"></a>
  6. ### 字符串拼接的几种方式
  7. 常用的字符串拼接方式有五种,分别是使用`+`、使用`concat`、使用`StringBuilder`、使用`StringBuffer`以及使用`StringUtils.join`
  8. - 如果要在一个循环体中进行字符串拼接,直接使用`StringBuilder`的方式是效率最高的
  9. - 如果不是在循环体中进行字符串拼接的话,直接使用`+`就好了
  10. - 如果在并发场景中进行字符串拼接的话,要使用`StringBuffer`来代替`StringBuilder`
  11. <a name="ElvqB"></a>
  12. ### JDK 6和JDK 7中substring的原理不同
  13. JDK6:当调用substring方法的时候,会创建一个新的string对象,但是这个string的值仍然指向堆中的同一个字符数组,如果你有一个很长很长的字符串,但是当你使用substring进行切割的时候你只需要很短的一段。这可能导致性能问题,因为你需要的只是一小段字符序列,但是你却引用了整个字符串(因为这个非常长的字符数组一直在被引用,所以无法被回收,就可能导致内存泄露)<br />![](https://cdn.nlark.com/yuque/0/2021/jpeg/12864446/1621326317710-b284c4bf-6862-4b94-9c34-fce3e2adcd77.jpeg#clientId=u82fcec15-6c51-4&from=paste&height=389&id=u91de4ec8&margin=%5Bobject%20Object%5D&originHeight=389&originWidth=650&originalType=url&status=done&style=none&taskId=u626b8c25-f5e3-4927-870e-07851422590&width=650)<br />JDK7:其使用new String创建了一个新字符串,避免对老字符串的引用,从而解决了内存泄露问题<br />![](https://cdn.nlark.com/yuque/0/2021/jpeg/12864446/1621326330128-16543b5c-3fed-46d6-ad29-6ea25f85de08.jpeg#clientId=u82fcec15-6c51-4&from=paste&height=389&id=ua38fd9b0&margin=%5Bobject%20Object%5D&originHeight=389&originWidth=650&originalType=url&status=done&style=none&taskId=u30c373d4-76c8-4415-afdc-a77a5e45f85&width=650)
  14. <a name="RdrjC"></a>
  15. ## 继承
  16. <a name="GWHml"></a>
  17. ### 继承示例
  18. ```java
  19. public class Demo {
  20. public static void main(String[] args) {
  21. Student student = new Student();
  22. student.setName("张三");
  23. student.setAge(18);
  24. student.setSchool("电子科技大学");
  25. System.out.println(student.getSchool());
  26. }
  27. }
  28. // 父类
  29. class Person {
  30. private String name;
  31. private int age;
  32. public String getName() {
  33. return name;
  34. }
  35. public void setName(String name) {
  36. this.name = name;
  37. }
  38. public int getAge() {
  39. return age;
  40. }
  41. public void setAge(int age) {
  42. this.age = age;
  43. }
  44. }
  45. // 子类
  46. class Student extends Person {
  47. private String school;
  48. public String getSchool() {
  49. return school;
  50. }
  51. public void setSchool(String school) {
  52. this.school = school;
  53. }
  54. }

方法覆写

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Student student = new Student();
  4. student.setName("张三");
  5. student.setAge(18);
  6. student.setSchool("电子科技大学");
  7. System.out.println(student.info());
  8. }
  9. }
  10. // 父类
  11. class Person {
  12. private String name;
  13. private int age;
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public int getAge() {
  21. return age;
  22. }
  23. public void setAge(int age) {
  24. this.age = age;
  25. }
  26. public String info() {
  27. return "姓名:" + name + ",年龄:" + age;
  28. }
  29. }
  30. // 子类
  31. class Student extends Person {
  32. private String school;
  33. public String getSchool() {
  34. return school;
  35. }
  36. public void setSchool(String school) {
  37. this.school = school;
  38. }
  39. public String info() {
  40. return super.info() + ",学校:" + school;
  41. }
  42. }

重载 VS 重写

  • 重载是一个编译期概念、重写是一个运行期间概念
  • 重载遵循所谓“编译期绑定”,即在编译时根据参数变量的类型判断应该调用哪个方法
  • 重写遵循所谓“运行期绑定”,即在运行的时候,根据引用变量所指向的实际对象的类型来调用方法
  • 因为在编译期已经确定调用哪个方法,所以重载并不是多态。而重写是多态。重载只是一种语言特性,是一种语法规则,与多态无关,与面向对象也无关。(注:严格来说,重载是编译时多态,即静态多态。但是,Java中提到的多态,在不特别说明的情况下都指动态多态)

    重写的条件

  • 参数列表必须完全与被重写方法的相同

  • 返回类型必须完全与被重写方法的返回类型相同
  • 访问级别的限制性一定不能比被重写方法的强
  • 访问级别的限制性可以比被重写方法的弱
  • 重写方法一定不能抛出新的检查异常或比被重写的方法声明的检查异常更广泛的检查异常
  • 重写的方法能够抛出更少或更有限的异常(也就是说,被重写的方法声明了异常,但重写的方法可以什么也不声明)
  • 不能重写被标示为final的方法
  • 如果不能继承一个方法,则不能重写这个方法

    重载的条件

  • 被重载的方法必须改变参数列表

  • 被重载的方法可以改变返回类型
  • 被重载的方法可以改变访问修饰符
  • 被重载的方法可以声明新的或更广的检查异常
  • 方法能够在同一个类中或者在一个子类中被重载

    final

  • final定义的类不能被继承

  • final定义的方法不能被覆盖
  • final定义的变量叫常量,值不能改变

    注解

    @Override(准确覆写)

    1. // 父类
    2. class Person {
    3. public String info() {
    4. return "AAA";
    5. }
    6. }
    7. // 子类
    8. class Student extends Person {
    9. @Override
    10. public String info() {
    11. return "BBB";
    12. }
    13. }

    @Deprecated(过时)

    ```java public class Demo { public static void main(String[] args) {
    1. Person person = new Person();
    2. System.out.println(person.fun());
    } } class Person { @Deprecated public String fun() {
    1. return "AAA";
    } }
  1. <a name="WxpM9"></a>
  2. ### @SuppressWarnings(压制警告)
  3. ```java
  4. public class Demo {
  5. @SuppressWarnings({"deprecation"})
  6. public static void main(String[] args) {
  7. Person person = new Person();
  8. System.out.println(person.fun());
  9. }
  10. }
  11. class Person {
  12. @Deprecated
  13. public String fun() {
  14. return "AAA";
  15. }
  16. }

多态

多态示例

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Message message1 = new Message();
  4. Message message2 = new TextMessage();
  5. Message message3 = new HtmlMessage();
  6. showMsg(message1);
  7. showMsg(message2);
  8. showMsg(message3);
  9. }
  10. public static void showMsg(Message message) {
  11. System.out.println(message.info());
  12. }
  13. }
  14. class Message {
  15. public String info() {
  16. return "Message";
  17. }
  18. }
  19. class TextMessage extends Message {
  20. public String info() {
  21. return "TextMessage";
  22. }
  23. }
  24. class HtmlMessage extends Message {
  25. public String info() {
  26. return "HtmlMessage";
  27. }
  28. }

instanceof

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Message message = new TextMessage();
  4. System.out.println(message.info1());
  5. if(message instanceof TextMessage) {
  6. TextMessage message2 = (TextMessage) message;
  7. System.out.println(message2.info2());
  8. }
  9. }
  10. }
  11. class Message {
  12. public String info1() {
  13. return "Message";
  14. }
  15. }
  16. class TextMessage extends Message {
  17. public String info2() {
  18. return "TextMessage";
  19. }
  20. }

Object

  1. public class Demo {
  2. public static void main(String[] args) {
  3. showMsg(new Message());
  4. }
  5. public static void showMsg(Object obj) {
  6. System.out.println(obj.getClass());
  7. if(obj instanceof Message) {
  8. Message message = (Message) obj;
  9. System.out.println(message.info());
  10. }
  11. }
  12. }
  13. class Message {
  14. public String info() {
  15. return "Message";
  16. }
  17. }

toString

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Person person = new Person();
  4. person.setName("张三");
  5. person.setAge(18);
  6. System.out.println(person);
  7. System.out.println(person.toString());
  8. }
  9. }
  10. class Person {
  11. private String name;
  12. private int age;
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public int getAge() {
  20. return age;
  21. }
  22. public void setAge(int age) {
  23. this.age = age;
  24. }
  25. @Override
  26. public String toString() {
  27. return "Person [name=" + name + ", age=" + age + "]";
  28. }
  29. }

equals(对象比较)

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Person person1 = new Person("张三", 18);
  4. Person person2 = new Person("张三", 18);
  5. System.out.println(person1.equals(person2));
  6. }
  7. }
  8. class Person {
  9. private String name;
  10. private int age;
  11. public Person(String name, int age) {
  12. this.name = name;
  13. this.age = age;
  14. }
  15. @Override
  16. public boolean equals(Object obj) {
  17. if (this == obj)
  18. return true;
  19. if (obj == null)
  20. return false;
  21. if (getClass() != obj.getClass())
  22. return false;
  23. Person other = (Person) obj;
  24. if (age != other.age)
  25. return false;
  26. if (name == null) {
  27. if (other.name != null)
  28. return false;
  29. } else if (!name.equals(other.name))
  30. return false;
  31. return true;
  32. }
  33. }

抽象类和抽象方法

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Message message = new TextMessage("MessageMessageMessage");
  4. message.showMsg();
  5. }
  6. }
  7. // 抽象类
  8. abstract class Message {
  9. private String msg;
  10. public Message(String msg) {
  11. this.msg = msg;
  12. }
  13. public String getMsg() {
  14. return msg;
  15. }
  16. // 抽象方法
  17. public abstract void showMsg();
  18. }
  19. // 继承抽象类
  20. class TextMessage extends Message {
  21. public TextMessage(String msg) {
  22. super(msg);
  23. }
  24. @Override
  25. public void showMsg() {
  26. System.out.println(getMsg());
  27. }
  28. }

包装类

包装类示例

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Byte byte1 = new Byte((byte) 127);
  4. Short short1 = new Short((short) 1024);
  5. Integer integer = new Integer(18);
  6. Long long1 = new Long(123456789L);
  7. Float float1 = new Float(3.14);
  8. Double double1 = new Double(3.14159);
  9. Boolean boolean1 = new Boolean(true);
  10. Character character = new Character('A');
  11. }
  12. }

定义布尔类型变量的注意事项

  • success还是isSuccess:不要加is,否则部分框架解析会引起序列化错误
  • boolean还是Boolean:局部变量用基本类型,POJO类属性、方法返回值和参数用包装类型

    1. boolean success
    2. boolean isSuccess
    3. Boolean success
    4. Boolean isSuccess

    自动装箱和自动拆箱

    1. public class Demo {
    2. public static void main(String[] args) {
    3. Integer x = 18;// 自动装箱
    4. int y = x;// 自动拆箱
    5. x++;// 可以计算
    6. System.out.println(x);
    7. System.out.println(y);
    8. // 先自动装箱为Double类型再赋值给obj
    9. Object obj = 3.14159;
    10. if(obj instanceof Double) {
    11. Double double1 = (Double) obj;
    12. System.out.println(double1 + 1.0);
    13. }
    14. // 注意一下
    15. Integer a = 127;
    16. Integer b = 127;
    17. System.out.println(a == b);// true
    18. Integer c = 128;
    19. Integer d = 128;
    20. System.out.println(c == d);// false
    21. System.out.println(c.equals(d));// true
    22. System.out.println(c.intValue() == d.intValue());// true
    23. }
    24. }

    接口

    接口示例

    1. public class Demo {
    2. public static void main(String[] args) {
    3. Message message = new TextMessage();
    4. System.out.println(message.getMsg());
    5. }
    6. }
    7. interface Message {
    8. String MSG = "MessageMessageMessage";
    9. String getMsg();
    10. }
    11. class TextMessage implements Message {
    12. @Override
    13. public String getMsg() {
    14. return Message.MSG + "AAAAAAA";
    15. }
    16. }

    接口多继承和多实现

    1. public class Demo {
    2. public static void main(String[] args) {
    3. Message3 message3 = new TextMessage();
    4. Message4 message4 = new TextMessage();
    5. System.out.println(message3.getMsg1());
    6. System.out.println(message3.getMsg2());
    7. System.out.println(message3.getMsg3());
    8. System.out.println(message4.getMsg4());
    9. }
    10. }
    11. // 简写形式
    12. interface Message1 {
    13. String MSG1 = "MessageMessageMessage";
    14. String getMsg1();
    15. }
    16. // 完整写法
    17. interface Message2 {
    18. public static final String MSG2 = "MessageMessageMessage";
    19. public abstract String getMsg2();
    20. }
    21. // 接口多继承
    22. interface Message3 extends Message1,Message2 {
    23. public abstract String getMsg3();
    24. }
    25. // 接口4
    26. interface Message4 {
    27. public abstract String getMsg4();
    28. }
    29. // 实现类
    30. class TextMessage implements Message3,Message4 {
    31. @Override
    32. public String getMsg1() {
    33. return "111";
    34. }
    35. @Override
    36. public String getMsg2() {
    37. return "222";
    38. }
    39. @Override
    40. public String getMsg3() {
    41. return "333";
    42. }
    43. @Override
    44. public String getMsg4() {
    45. return "444";
    46. }
    47. }

    接口增强

    1. public class Demo {
    2. public static void main(String[] args) {
    3. Message message = new TextMessage();
    4. System.out.println(message.getMsg());
    5. System.out.println(message.fun1());
    6. System.out.println(Message.fun2());
    7. }
    8. }
    9. // 增强的接口
    10. interface Message {
    11. public String MSG1 = "MessageMessageMessage";
    12. public String getMsg();
    13. public default String fun1() {
    14. return "BBBBBB";
    15. }
    16. public static String fun2() {
    17. return "CCCCCC";
    18. }
    19. }
    20. // 实现类
    21. class TextMessage implements Message {
    22. @Override
    23. public String getMsg() {
    24. return MSG1 + "AAAAAAAAAA";
    25. }
    26. }

    设计模式

    工厂设计模式

    1. // 客户端
    2. public class Demo {
    3. public static void main(String[] args) {
    4. Food food = Factory.getInstance(args[0]);
    5. food.eat();
    6. }
    7. }
    8. // 食物接口
    9. interface Food {
    10. public void eat();
    11. }
    12. // 面包实现
    13. class Bread implements Food {
    14. public void eat() {
    15. System.out.println("吃面包");
    16. }
    17. }
    18. // 牛奶实现
    19. class Milk implements Food {
    20. public void eat() {
    21. System.out.println("喝牛奶");
    22. }
    23. }
    24. // 工厂
    25. class Factory {
    26. public static Food getInstance(String type) {
    27. if("bread".equals(type)) {
    28. return new Bread();
    29. }else if("milk".equals(type)) {
    30. return new Milk();
    31. }else {
    32. return null;
    33. }
    34. }
    35. }

    编译代码:javac Demo.java
    运行程序:java Demo bread
    运行程序:java Demo milk

    代理设计模式

    1. // 客户端
    2. public class Demo {
    3. public static void main(String[] args) {
    4. Food food = new FoodProxy(new Bread());
    5. food.eat();
    6. }
    7. }
    8. // 食物接口
    9. interface Food {
    10. public void eat();
    11. }
    12. // 面包实现
    13. class Bread implements Food {
    14. public void eat() {
    15. System.out.println("吃面包");
    16. }
    17. }
    18. // 食物代理
    19. class FoodProxy implements Food {
    20. private Food food;
    21. public FoodProxy(Food food) {
    22. this.food = food;
    23. }
    24. public void eat() {
    25. System.out.println("吃之前处理");
    26. food.eat();
    27. System.out.println("吃之后处理");
    28. }
    29. }

    泛型

    基本定义

    1. public class Demo {
    2. public static void main(String[] args) {
    3. Message<String> message = new Message<String>("文本消息");
    4. String msg = message.getMsg();
    5. System.out.println(msg);
    6. // 简写形式
    7. Message<Integer> message2 = new Message<>(18);
    8. System.out.println(message2.getMsg());
    9. }
    10. }
    11. // 定义泛型
    12. class Message<T> {
    13. private T msg;
    14. public Message(T msg) {
    15. this.msg = msg;
    16. }
    17. public T getMsg() {
    18. return msg;
    19. }
    20. public void setMsg(T msg) {
    21. this.msg = msg;
    22. }
    23. }

    泛型通配符

    1. public class Demo {
    2. public static void main(String[] args) {
    3. Message<Integer> message = new Message<Integer>(18);
    4. Message<Long> message2 = new Message<Long>(123456789L);
    5. printMsg1(message);
    6. printMsg1(message2);
    7. printMsg2(message);
    8. printMsg2(message2);
    9. printMsg3(message);
    10. printMsg3(message2);
    11. }
    12. @SuppressWarnings("rawtypes")
    13. public static void printMsg1(Message message) {
    14. System.out.println(message.getMsg());
    15. }
    16. public static void printMsg2(Message<?> message) {
    17. System.out.println(message.getMsg());
    18. }
    19. // 指定上限
    20. public static void printMsg3(Message<? extends Number> message) {
    21. System.out.println(message.getMsg());
    22. }
    23. // 指定下限
    24. public static void printMsg4(Message<? super String> message) {
    25. System.out.println(message.getMsg());
    26. }
    27. }
    28. class Message<T> {
    29. private T msg;
    30. public Message(T msg) {
    31. this.msg = msg;
    32. }
    33. public T getMsg() {
    34. return msg;
    35. }
    36. public void setMsg(T msg) {
    37. this.msg = msg;
    38. }
    39. }

    泛型接口

    1. public class Demo {
    2. public static void main(String[] args) {
    3. Message<Integer> message = new MessageImpl1<Integer>();
    4. System.out.println(message.echo(18));
    5. Message<String> message2 = new MessageImpl2();
    6. System.out.println(message2.echo("AAAA"));
    7. }
    8. }
    9. // 泛型接口
    10. interface Message<T> {
    11. public String echo(T t);
    12. }
    13. // 泛型实现1
    14. class MessageImpl1<T> implements Message<T> {
    15. public String echo(T t) {
    16. return "MessageImpl1" + t;
    17. }
    18. }
    19. //泛型实现2
    20. class MessageImpl2 implements Message<String> {
    21. public String echo(String t) {
    22. return "MessageImpl1" + t;
    23. }
    24. }

    泛型方法

    ```java import java.util.Arrays;

public class Demo { public static void main(String[] args) { Integer[] arr = fun(1,2,3,4,5); System.out.println(Arrays.toString(arr)); }

  1. // 泛型方法
  2. @SuppressWarnings("unchecked")
  3. public static <T> T[] fun(T... args) {
  4. return args;
  5. }

}

  1. <a name="um04k"></a>
  2. ## 包
  3. <a name="M9vgj"></a>
  4. ### 包的定义
  5. ```java
  6. // 定义包
  7. package com.lin1118;
  8. public class Demo {
  9. public static void main(String[] args) {
  10. System.out.println("Hello 世界!");
  11. }
  12. }

编译代码:javac -d . Demo.java
运行程序:java com.lin1118.Demo

导包

  1. package com.lin1118;
  2. public class Message {
  3. public String getMsg() {
  4. return "Message1118";
  5. }
  6. }
  1. package com.lin0216;
  2. public class Message {
  3. public String getMsg() {
  4. return "Message0216";
  5. }
  6. }
  1. package com.lin1234;
  2. public class TextMessage {
  3. public String getMsg() {
  4. return "TextMessage";
  5. }
  6. }
  1. package com.lin1223;
  2. public class HtmlMessage {
  3. public static String getAAA() {
  4. return "AAA";
  5. }
  6. public static String getBBB() {
  7. return "BBB";
  8. }
  9. }
  1. // 导入这个类
  2. import com.lin1118.Message;
  3. // 导入这个包下所有类
  4. import com.lin1234.*;
  5. // 静态导入
  6. import static com.lin1223.HtmlMessage.*;
  7. public class Demo {
  8. public static void main(String[] args) {
  9. // java.lang包下面的类会自动导入比如: java.lang.String
  10. System.out.println(new String("Hello"));
  11. // 这里使用的是: com.lin1118.Message
  12. System.out.println(new Message().getMsg());
  13. // 本Demo程序中有两个Message,所以需要区分一下,下面使用的是: com.lin0216.Message
  14. System.out.println(new com.lin0216.Message().getMsg());
  15. // 下面使用的是: com.lin1234.TextMessage
  16. System.out.println(new TextMessage().getMsg());
  17. // 下面使用的是: com.lin1223.HtmlMessage
  18. System.out.println(getAAA());
  19. System.out.println(getBBB());
  20. }
  21. }

访问控制权限

访问范围 private default protected public
同一包中的同一类
同一包中的不同类 ×
不同包的子类 × ×
不同包的所有类 × × ×

单例

饿汉式

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Massage.getInstance().fun();
  4. }
  5. }
  6. // 单例:饿汉式
  7. class Massage {
  8. private static final Massage MASSAGE = new Massage();
  9. private Massage() {
  10. }
  11. public static Massage getInstance() {
  12. return MASSAGE;
  13. }
  14. public void fun() {
  15. System.out.println("AAA");
  16. }
  17. }

懒汉式

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Massage.getInstance().fun();
  4. }
  5. }
  6. // 单例:懒汉式
  7. class Massage {
  8. private static Massage massage;
  9. private Massage() {
  10. }
  11. public static Massage getInstance() {
  12. if(massage == null) massage = new Massage();
  13. return massage;
  14. }
  15. public void fun() {
  16. System.out.println("AAA");
  17. }
  18. }

枚举

枚举示例

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println(new Person("张三", 18, Sex.MALE));
  4. System.out.println(new Person("李四", 19, Sex.FEMALE));
  5. // 遍历所有枚举值
  6. for(Sex sex : Sex.values()) {
  7. System.out.println(sex.ordinal() + ":" + sex.name());
  8. }
  9. // 用于switch判断
  10. Sex sex = Sex.MALE;
  11. switch (sex) {
  12. case MALE:
  13. System.out.println("男");
  14. break;
  15. default:
  16. System.out.println("女");
  17. break;
  18. }
  19. }
  20. }
  21. enum Sex {
  22. MALE,FEMALE;
  23. }
  24. class Person {
  25. private String name;
  26. private int age;
  27. private Sex sex;
  28. public Person(String name, int age, Sex sex) {
  29. this.name = name;
  30. this.age = age;
  31. this.sex = sex;
  32. }
  33. public String toString() {
  34. return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
  35. }
  36. }

枚举结构

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println(new Person("张三", 18, Sex.MALE));
  4. System.out.println(new Person("李四", 19, Sex.FEMALE));
  5. Message message = Sex.MALE;
  6. System.out.println(message.getMsg());
  7. }
  8. }
  9. // 接口
  10. interface Message {
  11. public String getMsg();
  12. }
  13. // 枚举实现接口
  14. enum Sex implements Message {
  15. // 实例
  16. MALE("男") {
  17. public String fun() {
  18. return title;
  19. }
  20. },FEMALE("女") {
  21. public String fun() {
  22. return title;
  23. }
  24. };
  25. // 属性
  26. protected String title;
  27. // 构造方法
  28. private Sex(String title) {
  29. this.title = title;
  30. }
  31. // toString方法
  32. public String toString() {
  33. return title;
  34. }
  35. // 实现接口的方法
  36. public String getMsg() {
  37. return title;
  38. }
  39. // 每个枚举实例必须实现此方法
  40. public abstract String fun();
  41. }
  42. class Person {
  43. private String name;
  44. private int age;
  45. private Sex sex;
  46. public Person(String name, int age, Sex sex) {
  47. this.name = name;
  48. this.age = age;
  49. this.sex = sex;
  50. }
  51. public String toString() {
  52. return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
  53. }
  54. }

异常

异常程序

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("开始");
  4. System.out.println(10/0);
  5. System.out.println("结束");
  6. }
  7. }

异常处理

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("开始");
  4. try {
  5. System.out.println(10/0);
  6. } catch (ArithmeticException e) {
  7. System.out.println("出异常了:" + e);
  8. // 输出异常信息
  9. e.printStackTrace();
  10. }
  11. System.out.println("结束");
  12. }
  13. }

finally

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("开始");
  4. try {
  5. System.out.println(10/2);
  6. } catch (ArithmeticException e) {
  7. System.out.println("出异常了:" + e);
  8. // 输出异常信息
  9. e.printStackTrace();
  10. } finally {
  11. System.out.println("出异常 或 不出异常 都会执行");
  12. }
  13. System.out.println("结束");
  14. }
  15. }
  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("开始");
  4. try {
  5. System.out.println(10/0);
  6. } finally {
  7. System.out.println("出异常 或 不出异常 都会执行");
  8. }
  9. System.out.println("结束");
  10. }
  11. }

多异常处理

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("开始");
  4. try {
  5. System.out.println(10 / 0);
  6. System.out.println("AAA".charAt(10));
  7. } catch (ArithmeticException e) {
  8. e.printStackTrace();
  9. } catch (Exception e) {
  10. e.printStackTrace();
  11. }
  12. System.out.println("结束");
  13. }
  14. }

throws

  1. public class Demo {
  2. public static void main(String[] args) {
  3. // 必须处理异常
  4. try {
  5. System.out.println(MyUtil.fun(10, 2));
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. }
  9. }
  10. }
  11. class MyUtil {
  12. public static int fun(int x, int y) throws Exception {
  13. return x /y;
  14. }
  15. }
  1. public class Demo {
  2. public static void main(String[] args) {
  3. // 可以不处理异常
  4. System.out.println(MyUtil.fun(10, 2));
  5. }
  6. }
  7. class MyUtil {
  8. public static int fun(int x, int y) throws RuntimeException {
  9. return x /y;
  10. }
  11. }

throw

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("AAA");
  4. if("aaa".contains("a")) {
  5. throw new RuntimeException("手动抛一个异常");
  6. }
  7. System.out.println("BBB");
  8. }
  9. }
  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("AAA");
  4. try {
  5. System.out.println(10/0);
  6. } catch (ArithmeticException e) {
  7. throw new RuntimeException("除数不能为0");
  8. }
  9. System.out.println("BBB");
  10. }
  11. }

自定义异常

  1. public class Demo {
  2. public static void main(String[] args) {
  3. System.out.println("AAA");
  4. try {
  5. System.out.println(10/0);
  6. } catch (ArithmeticException e) {
  7. throw new MyException("除数不能为0");
  8. }
  9. System.out.println("BBB");
  10. }
  11. }
  12. // 自定义异常
  13. @SuppressWarnings("serial")
  14. class MyException extends RuntimeException {
  15. public MyException(String message) {
  16. super(message);
  17. }
  18. }

assert(断言)

  1. public class Demo {
  2. public static void main(String[] args) {
  3. int x = 10/2;
  4. assert x==6 : "x的值不是6";
  5. }
  6. }

编译代码:javac Demo.java
运行程序:java -ea Demo

内部类

内部类示例

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Outer outer = new Outer();
  4. outer.fun();
  5. }
  6. }
  7. class Outer {
  8. private String msg = "Hello";
  9. public void fun() {
  10. Inner inner = new Inner();
  11. inner.print();
  12. }
  13. class Inner {
  14. public void print() {
  15. System.out.println(msg);
  16. }
  17. }
  18. }

new内部类

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Outer outer = new Outer();
  4. outer.fun();
  5. Outer.Inner inner = new Outer().new Inner();
  6. inner.print();
  7. }
  8. }
  9. class Outer {
  10. private String msg = "Outer";
  11. public void fun() {
  12. Inner inner = new Inner();
  13. inner.print();
  14. System.out.println(inner.info);
  15. }
  16. class Inner {
  17. private String info = "Inner";
  18. public void print() {
  19. System.out.println(msg);
  20. }
  21. }
  22. }

私有内部类

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Outer outer = new Outer();
  4. outer.fun();
  5. // Inner用private修饰后下面就不能这样使用了
  6. // Outer.Inner inner = new Outer().new Inner();
  7. // inner.print();
  8. }
  9. }
  10. class Outer {
  11. private String msg = "Outer";
  12. public void fun() {
  13. Inner inner = new Inner();
  14. inner.print();
  15. System.out.println(inner.info);
  16. }
  17. private class Inner {
  18. private String info = "Inner";
  19. public void print() {
  20. System.out.println(msg);
  21. }
  22. }
  23. }

内部接口

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Channel channel = new ChannelImpl();
  4. channel.send(((ChannelImpl)channel).new MessageImpl());
  5. }
  6. }
  7. // 有内部接口
  8. interface Channel {
  9. public void send(Message message);
  10. interface Message {
  11. public String getContent();
  12. }
  13. }
  14. // 实现接口
  15. class ChannelImpl implements Channel {
  16. public void send(Message message) {
  17. System.out.println("发送消息:" + message.getContent());
  18. }
  19. // 不实现编译也可以通过
  20. class MessageImpl implements Message {
  21. public String getContent() {
  22. return "Hi Hello";
  23. }
  24. }
  25. }

内部抽象类

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Channel channel = new ChannelImpl();
  4. channel.send(((ChannelImpl)channel).new MessageImpl());
  5. }
  6. }
  7. // 有内部抽象类
  8. interface Channel {
  9. public void send(Message message);
  10. abstract class Message {
  11. public abstract String getContent();
  12. }
  13. }
  14. // 实现接口
  15. class ChannelImpl implements Channel {
  16. public void send(Message message) {
  17. System.out.println("发送消息:" + message.getContent());
  18. }
  19. // 不实现编译也可以通过
  20. class MessageImpl extends Message {
  21. public String getContent() {
  22. return "Hi Hello";
  23. }
  24. }
  25. }

接口内部实现

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Channel channel = Channel.getInstance();
  4. channel.send();
  5. }
  6. }
  7. // 接口内部实现
  8. interface Channel {
  9. public void send();
  10. class ChannelImpl implements Channel {
  11. public void send() {
  12. System.out.println("Hello");
  13. }
  14. }
  15. public static Channel getInstance() {
  16. return new ChannelImpl();
  17. }
  18. }

静态内部类

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Outer.Inner inner = new Outer.Inner();
  4. inner.print();
  5. }
  6. }
  7. class Outer {
  8. private static final String MSG = "Hello";
  9. static class Inner {
  10. public void print() {
  11. System.out.println(MSG);
  12. }
  13. }
  14. }

静态内部接口

  1. public class Demo {
  2. public static void main(String[] args) {
  3. MessageWarp.send(new DefaultMessage(), new NetChannel());
  4. }
  5. }
  6. interface MessageWarp {
  7. static interface Message {
  8. public String getContent();
  9. }
  10. static interface Channel {
  11. public boolean connect();
  12. }
  13. public static void send(Message message, Channel channel) {
  14. if(channel.connect()) {
  15. System.out.println("发送消息:" + message.getContent());
  16. }else {
  17. System.out.println("连接失败");
  18. }
  19. }
  20. }
  21. class DefaultMessage implements MessageWarp.Message {
  22. public String getContent() {
  23. return "Hello";
  24. }
  25. }
  26. class NetChannel implements MessageWarp.Channel {
  27. public boolean connect() {
  28. return true;
  29. }
  30. }

方法里定义内部类

  1. public class Demo {
  2. public static void main(String[] args) {
  3. new Outer().fun(123456);
  4. }
  5. }
  6. class Outer {
  7. private String msg = "Hello";
  8. public void fun(long time) {
  9. final String info = "Info";
  10. class Inner {
  11. public void print() {
  12. System.out.println(msg);
  13. System.out.println(time);
  14. System.out.println(info);
  15. }
  16. }
  17. new Inner().print();
  18. }
  19. }

匿名内部类

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Message message = new MessageImpl();
  4. message.send("Hello");
  5. // 匿名内部类
  6. Message message2 = new Message() {
  7. public void send(String str) {
  8. System.out.println(str);
  9. }
  10. };
  11. message2.send("Hello Hi");
  12. }
  13. }
  14. interface Message {
  15. public void send(String str);
  16. }
  17. class MessageImpl implements Message {
  18. public void send(String str) {
  19. System.out.println(str);
  20. }
  21. }

接口里面匿名内部类

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Message.getInstance().send("Hi");
  4. }
  5. }
  6. interface Message {
  7. public void send(String str);
  8. public static Message getInstance() {
  9. return new Message() {
  10. public void send(String str) {
  11. System.out.println(str);
  12. }
  13. };
  14. }
  15. }

Lambda表达式

  1. public class Demo {
  2. public static void main(String[] args) {
  3. // 匿名内部类写法
  4. Message message = new Message() {
  5. public void send(String str) {
  6. System.out.println(str);
  7. }
  8. };
  9. message.send("Hi");
  10. // Lambda表达式写法
  11. Message message1 = (str) -> {
  12. System.out.println(str);
  13. };
  14. message1.send("Hello");
  15. // 方法没有参数
  16. Message2 message2 = () -> {
  17. System.out.println("AAAAA");
  18. };
  19. message2.send();
  20. // 多个参数
  21. MyMath myMath = (x,y) -> {
  22. System.out.println("------");
  23. return x + y;
  24. };
  25. System.out.println(myMath.add(10, 20));
  26. // 只有一句,省略return
  27. MyMath myMath2 = (x,y) -> x + y;
  28. System.out.println(myMath2.add(10, 20));
  29. }
  30. }
  31. // 函数式接口
  32. @FunctionalInterface
  33. interface Message {
  34. public void send(String str);
  35. }
  36. // 方法没有参数
  37. @FunctionalInterface
  38. interface Message2 {
  39. public void send();
  40. }
  41. // 接口
  42. interface MyMath {
  43. public int add(int x, int y);
  44. }

方法引用

  1. public class Demo {
  2. public static void main(String[] args) {
  3. // 静态方法引用
  4. Function1<Integer,String> fun1 = String :: valueOf;
  5. String str = fun1.change(100);
  6. System.out.println(str.length());
  7. // 实例方法引用
  8. Function2<String> fun2 = "Hello" :: toUpperCase;
  9. System.out.println(fun2.upper());
  10. // 引用指定类中的方法
  11. Function3<String> fun3 = String :: compareTo;
  12. System.out.println(fun3.compare("a", "A"));
  13. // 构造方法的引用
  14. Function4<Person> fun4 = Person :: new;
  15. System.out.println(fun4.create("张三", 18));
  16. }
  17. }
  18. @FunctionalInterface
  19. interface Function1<P,R> {
  20. public R change(P p);
  21. }
  22. @FunctionalInterface
  23. interface Function2<R> {
  24. public R upper();
  25. }
  26. @FunctionalInterface
  27. interface Function3<P> {
  28. public int compare(P p1, P p2);
  29. }
  30. @FunctionalInterface
  31. interface Function4<R> {
  32. public R create(String s, int a);
  33. }
  34. // 类
  35. class Person {
  36. private String name;
  37. private int age;
  38. public Person(String name, int age) {
  39. this.name = name;
  40. this.age = age;
  41. }
  42. public String toString() {
  43. return "Person [name=" + name + ", age=" + age + "]";
  44. }
  45. }

函数式接口

  1. import java.util.function.Consumer;
  2. import java.util.function.Function;
  3. import java.util.function.Predicate;
  4. import java.util.function.Supplier;
  5. public class Demo {
  6. public static void main(String[] args) {
  7. Function<String,Boolean> function = "**Hello" :: startsWith;
  8. System.out.println(function.apply("**"));
  9. Consumer<String> consumer = System.out :: println;
  10. consumer.accept("Hello");
  11. Supplier<String> supplier = "Hello" :: toLowerCase;
  12. System.out.println(supplier.get());
  13. Predicate<String> predicate = "Hello" :: equalsIgnoreCase;
  14. System.out.println(predicate.test("HELLO"));
  15. }
  16. }

Eclipse

下载网址:https://www.eclipse.org/downloads/packages/
下载选择:Eclipse IDE for Enterprise Java and Web Developers