目录
异常处理
package com.jf.java;
import java.util.*;
/*
异常处理:
1. Throwable -> (Error or Exception)
2. Exception -> (Compile error and Execute error)
3. 异常会导致程序中断,无法继续执行
4. 在开发中,用try语句把有可能出现的异常包裹起来
5. 处理异常会让程序运行起来
6. catch可以有多个,顺序从子类到父类
7. finally无论代码是否捕捉到异常都会执行的代码块
8. try不能单独存在
9. try、catch、finally三个代码中变量的作用域分别独立而不能相互访问
10. 多个catch同时存在的时候,java虚拟机只会匹配其中一个异常类或其子类,执行一个catch块,而不执行其他的代码块
ArithmeticException
ArrayIndexOfBoundsException
NullPointerException
InputMismatchException
Exception
RuntimeException
ClassCastException
ClassNotFoundException
DataFormatException
*/
public class Test{
public static void main(String[] args) {
// System.out.println("hello world");
// divsion(2, 0);
// method();
//
// int result = div2(2,0);
// System.out.println(result);
input();
}
private static void divsion(int a, int b) {
int[] arr = {1,2,3,4,5}; // 数组
int[] arr1 = null; // 空数组
try {
System.out.println(arr[5]); // 越界检测
int div = a / b; // 除法运算检测
System.out.println(div);
System.out.println(arr1); // 空指针异常
} catch (ArithmeticException e) { // 算术异常
System.out.println("除数不能为零");
} catch (ArrayIndexOutOfBoundsException e) { // 数组下标越界异常
System.out.println("数组下标越界");
} catch (NullPointerException e){
System.out.println("空指针异常"); // 数组空指针异常
} catch(Exception e){
System.out.println("出错了");
} finally {// 最终 final finalize finally 之间的区别
System.out.println("程序1结束");
}
}
private static int method() {
int a = 10;
int b = 5;
try {
System.out.println("a="+a);
System.out.println("b="+b);
int c = a / b;
System.out.println("a/b="+c);
}catch(Exception e){
// 代码测试使用
e.printStackTrace();
}finally {
System.out.println("程序2结束");
}
return -1;
}
private static int div2(int a, int b) throws ArithmeticException{
try {
int c = a / b;
return c;
} catch(ArithmeticException e) {
throw new ArithmeticException("除数不能为零");
// java.lang.ArithmeticException: 除数不能为零
}
}
private static void input() {
// ctrl + shift + o 导包
Scanner input = new Scanner(System.in);
try{
int num = input.nextInt();
System.out.println(num);
}catch(InputMismatchException e){
System.out.println("输入的类型不匹配");
}
input.close();
}
}
输出结果:
hello world
数组下标越界
程序1结束
a=10
b=5
a/b=2
程序2结束
Exception in thread "main" java.lang.ArithmeticException: 除数不能为零
at com.jf.java.Test.div2(Test.java:80)
at com.jf.java.Test.main(Test.java:33)
a
输入的类型不匹配
1
1
登录操作的微型项目
LoginDemo.java
package com.jf.java;
/*
* 自定义异常
* 受检异常: Exception的子类或者间接子类, 必须在编译期内进行捕获, 否则就会报错, 必须显示使用try...catch...
* 非受检异常: RuntimeException的子类或者间接子类, 在运行期检查, 在调用抛出这个异常的方法时, 可以不用显示的使用try...catch...
*/
import java.util.Scanner;
public class LoginDemo {
public static void main(String[] args){
System.out.println("请输入用户名");
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println("请输入密码");
String password = input.nextLine();
UserService us = new UserService();
try {
User user = us.login(name, password);
System.out.println("登陆成功!!!");
System.out.println(user);
} catch (MyException e) {
e.printStackTrace();
}
input.close();
}
}
User.java
package com.jf.java;
public class User {
private String username;
private String password;
private String sex;
private int age;
public User() {
super();
}
public User(String username, String password, String sex, int age) {
super();
this.username = username;
this.password = password;
this.sex = sex;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", sex=" + sex + ", age=" + age + "]";
}
}
UserService.java
package com.jf.java;
public class UserService{
public User login(String username, String password)throws MyException {
if(!"admin".equals(username)) {
throw new MyException("用户名错误");
}
if(!"12345".equals(password)) {
throw new MyException("密码错误");
}
User user = new User("admin","12345","男",18); // 用户名 和 密码都正确
return user;
}
}
MyExcaption.java
package com.jf.java;
public class MyException extends Exception{ // 继承父类 Exception
public MyException() { // 无参构造方法
super();
}
public MyException(String message) {
super(message); // 有参构造方法
}
}
请输入用户名
admin
请输入密码
12345
登陆成功!!!
User [username=admin, password=12345, sex=男, age=18]
String 类原理分析
package com.jf.java1;
public class Test1 {
public static void main(String[] args) {
// ①直接赋值(推荐使用)
String name = "name";
// ②使用new关键字创建对象
String username = new String("name");
String name1 = "name"; //对象的重复利用
System.out.println(name==username); // false
System.out.println(name==name1); // true
// 代码实例:4种情况分析
// ①直接赋值字符串连接时,考虑编译期和运行期
// 如果在编译器可以被确定,那么就使用已有的对象,否则会创建新的对象
String a = "a";
String a1 = a+1;
String a2 = "a1";
System.out.println(a1==a2); // false
final String b = "b"; // 编译器被确定了
String b1 = b+"1";
String b2 = "b1";
System.out.println(b1==b2); // true
String c = getC();
String c1 = c + "1";
String c2 = "c1";
System.out.println(c1==c2); // false
final String d = getD(); // 不在运行期出结果
String d1 = d + "1";
String d2 = "d1";
System.out.println(d1==d2); // false
}
private static String getC() {
return "c";
}
private static String getD() {
return "d";
}
}
输出结果:
false
true
false
true
false
false
字符串的常用方法
package com.jf.java1;
/*
* 字符串的常用方法
*/
import java.util.Arrays;
public class StringDemo {
public static void main(String[] args) {
String str = "dhiuwghdiuwuiq378267";
char s = str.charAt(2);
System.out.println(s);
System.out.println(str.toCharArray());
char[] cs = {'a','b','c'};
String s1 = new String(cs); // 按住 F3 可以提取源码
System.out.println(s1); // abc
String s2 = new String(cs,0,1);
System.out.println(s2); // a 包首不包尾
System.out.println(Arrays.toString(str.getBytes())); // 字节与字符串
// ① 给定字符查询是否为这个字符开始
boolean isCharStart = str.startsWith("h"); // h is not a character of the string
System.out.println(isCharStart);
// ② 给定字符查询是否为这个字符结尾
String s3 = "7";
boolean isCharEnd = str.endsWith(s3); // 7 is the end part of the string
System.out.println(isCharEnd);
// ③ 给定范围查询字符
boolean isChar = str.startsWith("h",1); // h 给定字符,1是从下标1开始
System.out.println(isChar);
// 替换字符串 替换 u 成 *
System.out.println(str.replaceAll("u", "*")); // dhi*wghdi*w*iq378267
// 把数字部分去掉 [0-9][a-z][A-Z]正则表达式
System.out.println(str.replaceAll("[0-9]", "")); // dhiuwghdiuwuiq
// 字符串截取
System.out.println(str.substring(0,4)); // dhiu
// 拆分字符串
System.out.println(Arrays.toString(str.split("g"))); // [dhiuw, hdiuwuiq378267]
// 查询是否包含给定的字符串
System.out.println(str.contains("q")); // true
// 根据给定的字符串返回位置的下标值
System.out.println(str.indexOf("u")); // 从开始位置查 3
System.out.println(str.lastIndexOf("u")); // 从末尾开始查 11
String emptyString = "";
System.out.println(emptyString.isEmpty()); // true
System.out.println(str.length()); // 长度:20
System.out.println(str.trim()); // 去除首末的space
System.out.println(str.concat(s2)); // 串联两个字符串
System.out.println(String.valueOf(65)); // 65
}
}
StringBuffer
package com.jf.java1;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer(32);//带容量的构造(建议)
// str.append("a");
// str.append("b");
// str.append("c");
// StringBuffer是解决字符串相加时带来的性能问题(常量与变量相加的性能问题)
// StringBuffer的内部实现采用字符数组,默认数组的长度为16,超过最长长度之后,动态扩展数组是原来长度*2+2
// 所以我们预知要添加的数据长度时,建议使用初始化容量的构造方法,来避免动态扩充的次数,从而提高效率
// 线程安全的,性能会受到影响
str.append("a").append("b").append("c");
str.delete(0, 1); // bc
str.insert(0, "b"); // bbc
str.reverse(); // cbb
System.out.println(str.toString());
}
}
StringBuilder
package com.jf.java1;
public class StringBuilderDemo {
public static void main(String[] args) {
// 面试题:
// StringBuffer与StringBuilder区别: StringBuilder 线程不安全,性能高,适合在单线程中使用,这种情况占多数
StringBuilder str = new StringBuilder();
// 字符串的相加操作:
// 1.多个变量相加时没有性能问题,在编译器优化
// 2.变量与变量相加会产生垃圾对象
String a = "a";
String b = a + "b";
System.out.println(b);
String empty = null;
for (int i=0;i<5;i++) {
empty += i; // 每次循环之后都会产生一个StringBuilder实现拼接,性能低,最好手动创建StringBuilder来拼接
}
System.out.println(empty);
}
}
程序国际化
package com.jf.java1;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Scanner;
/*
* 程序国际化
* ResouceBundle 属性文本,是利用键值对的方式进行存储(key-value)
* getString(); 获取信息
*/
public class LocalDemo {
public static void main(String[] args) {
// 创建一个本地语言环境对象,该对象会根据参数设置来自动选择与之相关的语言环境
// 参数含义: zh-语言 CN-地区
Locale Local_CN = new Locale("zh","CN");
Locale Local_US = new Locale("en","US");
// 获取当前系统默认的语言环境
// Locale locale_default = Locale.getDefault();
Scanner input = new Scanner(System.in);
ResourceBundle r = ResourceBundle.getBundle("com.jf.java1.info",Local_CN);
System.out.println(r.getString("system.name"));
System.out.println(r.getString("input.username"));
String username = input.nextLine();
System.out.println(r.getString("input.password"));
String password = input.nextLine();
if (username.equals("admin")&&password.equals("123")){
System.out.println(r.getString("login.success"));
// 动态文本格式化
String welcome = r.getString("welcome.come");
String message = MessageFormat.format(welcome, username);
System.out.println(message);
}else {
System.out.println(r.getString("login.error"));
}
input.close();
}
}
输出结果
员工管理系统
用户名输入
admin
密码输入
123
登录成功!
欢迎您,admin
info_zh_CN_properties
system.name=\u5458\u5DE5\u7BA1\u7406\u7CFB\u7EDF
input.username=\u7528\u6237\u540D\u8F93\u5165
input.password=\u5BC6\u7801\u8F93\u5165
login.success=\u767B\u5F55\u6210\u529F\uFF01
login.error=\u767B\u5F55\u5931\u8D25\uFF01
welcome.come=\u6B22\u8FCE\u60A8,{0}
info_en_US_properties
system.name=EMP Mananger System
input.username=Input UserName
input.password=Input Password
login.success=Login Success!
login.error=Login failed!
welcome.come=welcome!!!
Random类 + Date类
package com.jf.java1;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;
public class MathRandomDateDemo {
public static void main(String[] args) {
System.out.println("输出PI的值:"+Math.PI);
System.out.println("输出绝对值:"+Math.abs(-10));
System.out.println("输出在0-1范围内Double类型的随机值:"+Math.random());
System.out.println("随机数:"+Math.random()*100);
System.out.println("根数:"+Math.sqrt(2)); // 1.414
// Random类: nextLong() nextDouble() nextBoolean() nextFloat() nextInt() nextInt(int n)
Random r = new Random();
double dou = r.nextDouble();
System.out.println(dou);
// 日期操作类: Date
/*
* 使用两个构造方法
* Date(long date) 参数是毫秒
* Date()
*/
Date date = new Date();
System.out.println(date); // Tue Oct 04 09:04:22 IRKT 2022
java.sql.Date sqlDate = new java.sql.Date(0);
System.out.println(sqlDate); // 1970-01-01
// Calendar类:
Calendar cal1 = Calendar.getInstance();
//Calendar cal2 = new GregorianCalendar();
/*
* YEAR MONTH DAY_OF_MONTH HOUR_OF_DAY MINUTE SECOND MILLISECOND
*/
int year = cal1.get(Calendar.YEAR); // 2022年
int month = cal1.get(Calendar.MONTH); // 十月
int day = cal1.get(Calendar.DAY_OF_MONTH);
StringBuilder str = new StringBuilder(50);
str.append(year).append(":"+(month+1)).append(":"+day);
System.out.println(str); // 2022:10:4 累死
// 日期格式化
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss SSS");
String nowDate = df.format(new Date());
System.out.println(nowDate);
}
}
Comparable 与 Comparator
package com.jf.java1;
/*
* 自定义对象,要实现比较
* 1. 可以实现Comparable接口的CompareTo的方法
*/
import java.util.Arrays;
import java.util.Comparator;
public class Test2 {
public static void main(String[] args) {
Person[] persons = {new Person("Mark",26),new Person("Jack",22),new Person("Felix",23)};
Arrays.sort(persons);
System.out.println("第一行比较:"+Arrays.toString(persons));
Animal[] animals = {new Animal(12),new Animal(19),new Animal(9)};
Arrays.sort(animals,new AnimalComparator());
System.out.println("第二行比较:"+Arrays.toString(animals));
}
}
class Person implements Comparable<Person>{ // Comparable<Person> !!!!!
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Person o) {
/*
* 年龄 从小到大 this.age - o.age;
* 年龄 从大到小 o.age - this.age;
*/
return o.age-this.age; // 第一行比较:[Person [name=Mark, age=26], Person [name=Felix, age=23], Person [name=Jack, age=22]]
}
}
class Animal{
private int age;
public Animal() {
super();
}
public Animal(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Animal [age=" + age + "]";
}
}
class AnimalComparator implements Comparator<Animal>{
@Override
public int compare(Animal o1, Animal o2) {
return o1.getAge()-o2.getAge(); // 第二行比较:[Animal [age=9], Animal [age=12], Animal [age=19]]
}
}
输出结果:
第一行比较:[Person [name=Mark, age=26], Person [name=Felix, age=23], Person [name=Jack, age=22]]
第二行比较:[Animal [age=9], Animal [age=12], Animal [age=19]]
Cloneable 接口
package com.jf.java1;
/*
* Cloneable接口:标记接口
*/
public class CloneDemo{
public static void main(String[] main) {
Bag bag = new Bag("channel",1200);
try {
Bag newBag = (Bag) bag.clone();
System.out.println("Old bag: "+bag);
System.out.println("New bag: "+newBag);
System.out.println(bag==newBag); // 两个是不同的两个对象
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
class Bag implements Cloneable{
private String name;
private int price;
public Bag() {
super();
}
public Bag(String name, int price) {
super();
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return price;
}
public void setAge(int age) {
this.price = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", price=" + price + "]";
}
// 重写Object中的clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
输出结果:
Old bag: Person [name=channel, price=1200]
New bag: Person [name=channel, price=1200]
false
SystemAndRuntime类
package com.jf.java1;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class SystemAndRuntimeDemo {
public static void main(String[] args) {
System.out.println("Success");
System.err.println("Failed");
// ① 系统中的拷贝数组
int[] arr = {1,2,3,4,5,6}; // src
int[] arr2 = new int[arr.length]; // des
// 0 src -> start 0 des -> start arr.length -> the length of the string
System.arraycopy(arr, 0, arr2, 0, arr.length);
System.out.println(Arrays.toString(arr2));
// ② 系统中获取时间
System.out.println("源初始:"+System.currentTimeMillis());
Date nowDate = new Date(System.currentTimeMillis());
DateFormat df = new SimpleDateFormat("HH:mm:ss");
String date = df.format(nowDate);
System.out.println(date);
// ③ 退出程序
// 0表示正常退出 非0表示异常退出
System.exit(0);
// ④ 垃圾回收 public static void gc();
// ⑤ 获取系统中的属性
System.out.println(System.getProperty("java.version"));//版本信息
System.out.println(System.getProperty("java.home"));//安装目录
/*
* os.name 操作系统的名称
* os.version 操作系统的版本
* user.name 用户的账户名称
* user.home 用户的主目录
* user.dir 用户当前工作目录
*/
// ⑥ Runtime类
Runtime rt = Runtime.getRuntime();
System.out.println("处理器的数量"+rt.availableProcessors()+"个");
System.out.println("JVM总内存书"+rt.totalMemory()+"byte");
System.out.println("JVM空闲内存书"+rt.freeMemory()+"byte");
System.out.println("JVM可用最大内存数"+rt.maxMemory()+"byte");
// 在单独的进程中执行的字符出命令
try {
rt.exec("notepad"); //打开笔记本
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 加载 C、C++编写的类库
// System.out.println(libname);
}
}
数字处理工具类
package com.jf.java1;
/*
* 数字处理工具类
*/
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.Arrays;
public class MathDemo {
public static void main(String[] args) {
System.out.println("----------------整数运算-----------------");
// ① 大整数运算
String val1 = "524156415613218";
String val2 = "235465416564786";
BigInteger int1 = new BigInteger(val1);
BigInteger int2 = new BigInteger(val2);
System.out.println(int1.add(int2));//+
System.out.println(int1.subtract(int2));//-
System.out.println(int1.multiply(int2));//*
System.out.println(int1.divide(int2));// /
System.out.println(int1.remainder(int2));// %
System.out.println(Arrays.toString(int1.divideAndRemainder(int2)));// /%
System.out.println("----------------小数运算-----------------");
// ② 大小数运算
String val3 = "265.4115415615365544";
String val4 = "4";
BigDecimal dec1 = new BigDecimal(val3);
BigDecimal dec2 = new BigDecimal(val4);
System.out.println(dec1.add(dec2));
System.out.println(dec1.subtract(dec2));
System.out.println(dec1.multiply(dec2));
System.out.println(dec1.divide(dec2));
System.out.println("----------------格式化运算-----------------");
// ③ 数字格式化
double pi = 3.1415926;
System.out.println(new DecimalFormat("0").format(pi)); // 3
System.out.println(new DecimalFormat("0.00").format(pi)); // 3.14
System.out.println(new DecimalFormat("00.000").format(pi)); // 03.142
System.out.println(new DecimalFormat("#").format(pi)); // 3 取整数
System.out.println(new DecimalFormat("#.##%").format(pi)); // 314.16% 以百分比计数,并取两位小数
// long类型的格式化
long num = 454154665;
System.out.println(new DecimalFormat("###,###%").format(num));
}
}
MD5工具类
package com.jf.java1;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
/*
* MD5工具类:Message Digest Algorithm 5 信息-摘要算法
*/
public class Test3 {
public static void main(String[] args) {
test(); // Extract the method from test
}
private static void test() {
String password = "admin123456";
String savePassword = "pmq7VoTEWWLYh1ZPCDRujQ==";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(password.getBytes("UTF-8"));
// 结果一:
System.out.println(Arrays.toString(bytes)); // [-90, 106, -69, 86, -124, -60, 89, 98, -40, -121, 86, 79, 8, 52, 110, -115]
// String mdStr = new String(bytes);
// System.out.println(mdStr); // �j�V��Yb؇VO4n�
// BASE64编码算法
// a-z A-Z 0-9
// 1.8版本
String str = Base64.getEncoder().encodeToString(bytes);
System.out.println(str); // pmq7VoTEWWLYh1ZPCDRujQ==
// 结果二:
byte[] bytes2 = Base64.getDecoder().decode(savePassword);
System.out.println(Arrays.toString(bytes2)); // [-90, 106, -69, 86, -124, -60, 89, 98, -40, -121, 86, 79, 8, 52, 110, -115]
// rt.jar -> sun.misc -> BASE64Decoder / BASEEncoder
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
MD5 用户登录案例
package com.jf.java1;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class LoginDemo {
final static String savePassword = "pmq7VoTEWWLYh1ZPCDRujQ==";
public static void main(String[] args) {
String password = "admin123456";
String savepassword = passwordEnter(password);
boolean Login = Login(savepassword);
System.out.println("输出的结果:"+Login);
}
public static boolean Login(String savepassword) {
if(savePassword.equals(savepassword)) {
return true;
}else {
return false;
}
}
public static String passwordEnter(String password) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(password.getBytes("UTF-8"));
String str = Base64.getEncoder().encodeToString(bytes);
return str;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
输出结果:
输出的结果:true (验证成功)
二叉树的代码演示
二叉树类:
package com.jf.java1;
public class BinaryTree {
private Node root;
public void add(int data){
if(root==null){
root = new Node(data);
}else{
root.addNode(data);
}
}
public void print(){
root.printNode();
}
public class Node{
private int data;
private Node left;
private Node right;
public Node(int data){
this.data = data;
}
public void addNode(int data){
if(this.data>data) {
if(left==null) {
left = new Node(data);
}else {
this.left.addNode(data);
}
}else {
if(right==null) {
right = new Node(data);
}else {
this.right.addNode(data);
}
}
}
// 中序遍历
public void printNode(){
if(this.left!=null) {
this.left.printNode();
}
System.out.print(this.data+"->");
if(this.right!=null) {
this.right.printNode();
}
}
}
}
实现类:
package com.jf.java1;
public class BinaryTreeDemo {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.add(8);
bt.add(10);
bt.add(3);
bt.add(14);
bt.add(6);
bt.add(2);
bt.add(19);
bt.add(1);
bt.print();
}
}
输出结果:
1->2->3->6->8->10->14->19->
JDK1.8新特性 lambda方法
package com.jf.java1;
import java.util.Arrays;
import java.util.Comparator;
public class LambdaDemo {
public static void main(String[] args) {
// 普通实现接口
IEat ieat1 = new IEatimp1();
ieat1.eat(); // ①
// 匿名接口
IEat ieat2 = new IEatimp1() {
public void eat() {
System.out.println("②");
}
};
ieat2.eat(); // ②
// lambda接口: no arguments
// 优点: 代码更加简洁,不会生成class文件
IEat ieat3 = ()->{
System.out.println("③"); // ③
};
ieat3.eat();
// 带参数的接口:
IUser iuser = (username,postcode)->{
System.out.println("我的名字是: "+username+",我的住址是: "+postcode);
};
iuser.user("Felix", "AB245QP");
// 带返回值的接口:
// IEat ieat4 = (int num)->{return num;};
// ieat4.eat(num);
// 参数中带final关键字
IUser iuser2 = (final String username,final String postcode)->{
System.out.println("我的名字是: "+username+",我的住址是: "+postcode);
};
iuser2.user("Mark", "AB246QP");
// Compartor lambda接口
Student[] students = {
new Student("张三",12),
new Student("李四",35),
new Student("王五",23)
};
// 对象排序
Arrays.sort(students,new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();
}
});
// lambda接口排序
// Comparator<Student> c = (o1,o2)->o1.getAge()-o2.getAge();
Arrays.sort(students,(o1,o2)->o1.getAge()-o2.getAge());
System.out.println(Arrays.toString(students));
// 在接口中的默认方法:
IEat def = ()->{};
def.print(); // default test
// 在接口中的静态方法
IEat.test(); // static test
}
}
interface IEat{
public void eat();
public default void print() {
System.out.println("default test");
};
public static void test() {
System.out.println("static test");
}
}
interface IUser{
public void user(final String username, final String postcode);
}
class IEatimp1 implements IEat{
@Override
public void eat() {
System.out.println("①");
}
}
class IUserimp1 implements IUser{
@Override
public void user(final String username, final String postcode) {
System.out.println("带参数的接口");
}
}
输出结果:
①
②
③
我的名字是: Felix,我的住址是: AB245QP
我的名字是: Mark,我的住址是: AB246QP
[Student [name=张三, age=12], Student [name=王五, age=23], Student [name=李四, age=35]]
default test
static test