Solution: Implementation of interfaces
Completion requirements
Class DateTime implements interfaces IDate and ITime
1 public interface IDate { 2 int getDay(); 3 int getMonth(); 4 int getYear(); 5 }
1 public interface ITime { 2 int getHour(); 3 int getMinute(); 4 int getSecond(); 5 }
1 import java.time.LocalDateTime; 2 import java.time.format.DateTimeFormatter; 3 4 public class DateTime implements IDate, ITime { // 2 interfaces are implemented 5 6 private int day, month, year, hour, minute, second; 7 8 DateTime() { 9 LocalDateTime now = LocalDateTime.now(); 10 day = Integer.parseInt(now.format(DateTimeFormatter.ofPattern("dd"))); 11 month = Integer.parseInt(now.format(DateTimeFormatter.ofPattern("MM"))); 12 year = Integer.parseInt(now.format(DateTimeFormatter.ofPattern("yyyy"))); 13 hour = Integer.parseInt(now.format(DateTimeFormatter.ofPattern("HH"))); 14 minute = Integer.parseInt(now.format(DateTimeFormatter.ofPattern("mm"))); 15 second = Integer.parseInt(now.format(DateTimeFormatter.ofPattern("ss"))); 16 } 17 18 public int getDay() { // these methods have to be defined in class 19 return day; 20 } 21 public int getMonth() { 22 return month; 23 } 24 public int getYear() { 25 return year; 26 } 27 public int getHour() { 28 return hour; 29 } 30 public int getMinute() { 31 return minute; 32 } 33 public int getSecond() { 34 return second; 35 } 36 }
1 public class Main { 2 3 public static void main(String[] args) { 4 DateTime dt = new DateTime(); 5 System.out.println("Date: " + dt.getDay() + "." + dt.getMonth() + "." + dt.getYear() 6 + "\tTime: " + dt.getHour() + ":" + dt.getMinute() + ":" + dt.getSecond()); 7 } 8 }
Last modified: Saturday, 18 May 2019, 8:36 PM