23.java介面預設方法和時間API

不畏未來!不念過去發表於2020-10-12

1.介面預設方法

1.1 介面預設方法的定義

  • 在java8之前,介面(interface)沒有提供任何具體的實現,介面定義的方法全部都是抽象方法
  • java8之後對介面做了進一步增強:
    1. 允許介面中可以新增使用default關鍵字,即預設方法,或者也可以叫做可擴充套件方法
    2. 介面裡可以宣告靜態方法,並且可以做具體實現
  • 預設方法與抽象方法的區別
    • 抽象方法必須要實現,預設方法不是,因為預設方法做了具體實現;這個介面中的預設方法可以通過子類繼承到這個預設方法,當然子類也可以重寫該預設方法。
  • 為了提高程式碼的可重用性,介面的預設方法有助於在擴充套件系統功能的同時,不對現有的繼承關係及類庫產生很大的影響,比如在java8中,java集合框架的collection介面增加stream()等預設方法,這些預設方法即增強了集合的功能,同時又保證對低版本jdk的相容。

1.2 案例1

public interface Animal{
    void fly();//飛
    
    void swim();//游泳
}
  • 假設定義了Animal介面,裡面定義了兩個方法,一個fly()飛方法,一個swim()游泳方法。
  • 當子類Brid鳥類實現Animal介面的時候就必須重寫這兩個方法,但是Brid鳥類只需要fly()方法不需要swim()方法,所以這樣方法重寫兩個方法勢必造成程式碼冗餘,那麼在介面中定義預設方法就體現出優勢了!

1.3 案例2

  • Animal類

    public interface Animal {
    	default void fly() {
    		System.out.println("鳥飛飛`````");
    	}
    	default void swim() {
    		System.out.println("魚游泳、、、、");
    	}
    }
    
  • Brid類

    public class Brid implements Animal{
    	
    //	public void showBrid() {
    //		this.fly();
    //		this.swim();
    //	}
    
    	@Override
    	public void fly() {
    		System.out.println("鳥在天上飛!");
    	}
    
    }
    
  • Fish類

    public class Fish implements Animal{
    
    	@Override
    	public void swim() {
    		System.out.println("魚在水裡遊!");
    	}
    	
    
    }
    
  • 測試

    public class Test {
    	public static void main(String[] args) {
    		Animal brid = new Brid();
    		brid.fly();
    		
    		Animal fish = new Fish();
    		fish.swim();
    				
    	}
    }
    

1.4介面中靜態方法

  • java8 之後可以在介面中定義靜態方法,因為介面不能被例項化,但是可以通過介面.方法名直接呼叫。

  • 案例1

    public interface Animal {
    	default void fly() {
    		System.out.println("鳥飛飛`````");
    	}
    	default void swim() {
    		System.out.println("魚游泳、、、、");
    	}
    	
    	public static void showAnimal() {
    		System.out.println("我是一個動物");
    	}
    }
    
    public class Test {
    	public static void main(String[] args) {
    		Animal brid = new Brid();
    		brid.fly();
    		
    		Animal fish = new Fish();
    		fish.swim();
    		
    		Animal.showAnimal();
    	}
    }
    
  • 案例2

    import java.util.function.Supplier;
    
    public interface AnimalFactory {
    	public static Animal create(Supplier<Animal> supplier) {
    		
    		return supplier.get();
    	}
    }
    
    public class Test {
    	public static void main(String[] args) {
    		//通過介面呼叫介面中的靜態方法
    		Animal brid = AnimalFactory.create(()->new Brid());
    		brid.fly();
    		
    		Animal fish = AnimalFactory.create(Fish::new);
    		fish.swim();
    	}
    }
    

2.日期API

  • java8新增很多對於日期的處理,如下:

2.1 LocalDate

  1. 案例1:

    import java.time.LocalDate;
    
    public class Test1 {
    	public static void main(String[] args) {
    		LocalDate date1 = LocalDate.of(2020, 10, 9);
    		LocalDate date2 = LocalDate.parse("2020-10-09");
    		LocalDate date3 = LocalDate.now();
    		System.out.println(date3);
    		
    		//獲取年月日
    		System.out.println(date3.getYear());
    		System.out.println(date3.getMonth());
    		System.out.println(date3.getMonthValue());
    		System.out.println(date3.getDayOfYear());
    		System.out.println(date3.getDayOfMonth());
    		System.out.println(date3.getDayOfWeek());
    		
    		//檢視該月有多少天
    		System.out.println(date3.lengthOfMonth());
    		//檢查是否是閏年
    		System.out.println(date3.isLeapYear());
    	}
    }
    
  2. 案例2:

    還可以通過get方法獲取年月日

    import java.time.LocalDate;
    import java.time.temporal.ChronoField;
    
    public class Test2 {
    	public static void main(String[] args) {
    		LocalDate date = LocalDate.now();
    		int year = date.get(ChronoField.YEAR);
    		int month = date.get(ChronoField.MONTH_OF_YEAR);
    		int day = date.get(ChronoField.DAY_OF_MONTH);
    		System.out.println(year+"-"+month+"-"+day);
    		System.out.println("本月第幾周:"+date.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH));
    	}
    }
    
  3. 案例3

    修改日期

    import java.time.LocalDate;
    import java.time.temporal.ChronoField;
    
    public class Test3 {
    	public static void main(String[] args) {
    		LocalDate date1 = LocalDate.of(2020, 10, 9);
    		date1 = date1.withDayOfMonth(30);//修改天數
    		System.out.println(date1);
    		
    		date1 = date1.with(ChronoField.DAY_OF_MONTH,25);//修改天數
    		System.out.println(date1);
    		
    		date1 = date1.plusYears(5);//增加
    		System.out.println(date1);
    	}
    }
    
  4. 案例4:

    將日期格式化轉換成字串

    import java.text.SimpleDateFormat;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.Date;
    
    public class Test {
    	public static void main(String[] args) {
    		LocalDate date = LocalDate.now();
    		String str1 = date.format(DateTimeFormatter.BASIC_ISO_DATE);
    		System.out.println(str1);
    		String str2 = date.format(DateTimeFormatter.ISO_LOCAL_DATE);
    		System.out.println(str2);
    		System.out.println(date.toString());
    		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    		String str3 = date.format(dtf);
    		System.out.println(str3);
    		
    		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    //		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    		Date time = new Date();
    		//格式化時間,獲取到年月日時分秒
    		String str4 = df.format(time);
    		System.out.println("java8之前的日期處理:"+str4);
    	
    		//將
    		LocalDate date2 = LocalDate.parse(str3,dtf);
    		System.out.println(date2);
    	}
    }
    

2.2 LocalTime

LocalTime是時分秒格式的時間

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Test1 {
	public static void main(String[] args) {
		LocalTime time = LocalTime.of(14, 29,35);
		time=LocalTime.parse("14:44:56");
		System.out.println(time);
		System.out.println(time.getHour());
		System.out.println(time.getMinute());
		System.out.println(time.getSecond());
	
		//將time轉換自定義格式
		LocalTime time2 = LocalTime.now();
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH時mm分ss秒");
		String time3 = time2.format(dtf);
		System.out.println(time3);
	}
}

2.3 LocalDateTime

LocalDateTime是年月日 時分秒格式的時間

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Test2 {
	public static void main(String[] args) {
		LocalDateTime dateTime1 = LocalDateTime.of(2020, 10,9,14,45,55);
		LocalDateTime dateTime2 = LocalDateTime.now();
		LocalDateTime dateTime = LocalDateTime.parse("2020-11-12T14:45:55");
		System.out.println(dateTime);
		
		String time = dateTime2.format(DateTimeFormatter.ofPattern("yyyy年/MM月/dd日 HH時mm分ss秒"));
		System.out.println(time);
		

	}
}

2.4Duration\Period求時間差

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;

public class Test {
	public static void main(String[] args) {
		LocalDateTime time1 = LocalDateTime.of(1992,1,11,5,1);
		LocalDateTime time2 = LocalDateTime.now();
		//求時間差
		Duration duration = Duration.between(time1, time2);
		//換算為天
		long days = duration.toDays();
		System.out.println(days);
		
		LocalDate time3 = LocalDate.of(1992,1,11);
		LocalDate time4 = LocalDate.now();
		//period類是用於localDate型別的時間差
		Period period = Period.between(time3, time4);
		long days2 = period.getDays();
		long months2 = period.getMonths();
		System.out.println("相差天數:"+days2);
		System.out.println("相差月份:"+months2);
		
	}
}

2.5 isAfter\isBefore判斷

import java.time.LocalDate;

public class Test {
	public static void main(String[] args) {
		LocalDate time1 = LocalDate.of(1997, 3, 15);
		LocalDate time2 = LocalDate.now();
		System.out.println("兩個時間相等嗎?"+time1.equals(time2));
		System.out.println("time1在time2之後嗎?"+time1.isAfter(time2));
		System.out.println("time1在time2之前嗎?"+time1.isBefore(time2));
	}
}

2.6MonthDay

import java.time.LocalDate;
import java.time.MonthDay;

public class Test {
	public static void main(String[] args) {
//		MonthDay monthDay = MonthDay.of(1, 11);
		LocalDate date = LocalDate.of(1997,3,15);
		MonthDay monthDay = MonthDay.of(date.getMonth(), date.getDayOfMonth());
		//monthDay用於存月-日時間
		MonthDay currentMonthDay = MonthDay.from(LocalDate.now());
		if(currentMonthDay.equals(monthDay)) {
			System.out.println("生日快樂!");
		}
	}
}

相關文章