java:interface_implementation

This is an old revision of the document!


A PCRE internal error occured. This might be caused by a faulty plugin

====== Υλοποίηση του Interface ====== Μία κλάση υλοποιεί ένα interface μόνο εάν υλοποιεί ΟΛΕΣ τις μεθόδους του interface. Έάν έστω και μία μέθοδος δεν υλοποιείται τότε η κλάση δεν υλοποιεί το interface. Σε συνέχεια του προηγούμενου παραδείγματος θα επιχειρήσουμε να δημιουργήσουμε δύο διαφορετικές κλάσεις που υλοποιούν το συγκεκριμένο //interface//. Οι κλάσεις αυτές είναι **SimpleTimer** και **StartStopTimer**. Και οι δύο κλάσεις παρέχουν την ίδια λειτουργικότητα. ===== SimpleTimer ===== <code java SimpleTimer.java> class SimpleTimer implements Timer { private long start_time, duration; private boolean running = false; public void setTimer(int seconds) { duration = seconds * 1000; } public boolean startTimer() { Date now = new Date(); if(duration > 0) { start_time = now.getTime(); running = true; } else { running = false; } return running; } public void stopTimer() { Date now = new Date(); if( running && now.getTime() > start_time) duration -= now.getTime() - start_time; running = false; } public boolean isRunning() { return running; } public boolean hasExpired() { Date now = new Date(); if( (running && now.getTime() - start_time >= duration) || duration <= 0 ) { start_time = 0L; duration = 0L; running = false; return true; } return false; } } </code> ===== StartStopTimer ===== <code java StartStopTimer.java> class StartStop implements Timer { private long start_time, duration; ArrayList starts = new ArrayList(); ArrayList stops = new ArrayList(); private boolean running = false; public void setTimer(int seconds) { duration = seconds * 1000; } public boolean startTimer() { long now = new Date().getTime(); if(!running) { starts.add(now); running = true; } return running; } public void stopTimer() { long now = new Date().getTime(); if(running) { stops.add(now); running = false; } } public boolean isRunning() { return running; } public boolean hasExpired() { if( !running ) return running; long runtime = 0L; for(int i=0; i<stops.size(); i++) { runtime += (long)((Long)stops.get(i) - (Long)starts.get(i)); } long now = new Date().getTime(); runtime += now - (Long)starts.get(stops.size()); if( running && runtime > duration ) { start_time = 0; duration = 0; running = false; return true; } return false; } } </code> Παραπάνω έχουμε υλοποιήσει το συγκεκριμένο //interface// μέσα από δύο διαφορετικές κλάσεις. Αν και η υλοποίηση των κλάσεων διαφέρει σημαντικά, η λειτουργικότητα που παρέχουν είναι ισοδύναμη. Μπορείτε να χρησιμοποιήσετε οποιαδήποτε από της δύο κλάσεις για να εξυπηρετήσετε τη λειτουργικότητα του //interface// **Timer** σε ένα πρόγραμμα. | Προηγούμενο : [[ java:interface_definition ]] | [[ :toc | Περιεχόμενα ]] | Επόμενο: [[ :java:interface_as_data_type | Το interface ως τύπος δεδομένων ]] |

java/interface_implementation.1490967228.txt.gz · Last modified: 2017/03/31 13:33 by gthanos