Περίγραμμα Aναλλοίωτοι Περιορισμοί ΕΠΛ133 - Διάλεξη 6η Παραβίαση ιδιωτικότητας, Κατασκευαστές αντιγραφείς (copy costructors). Μεταλλάξιμες και μη μεταλλάξιμες κλάσεις Βιβλιοθήκες Java και Javadoc Kεφ. 5, Savitch Επίλυση Υπολογιστικών Προβλημάτων 1 2 Αναλλοίωτοι Περιορισμοί (Class Ivariats) I object-orieted programmig, a class ivariat (or type ivariat) is a ivariat used to costrai objects of a class. Methods of the class should preserve the ivariat. The class ivariat costrais the state stored i the object. Esures that objects will always meet predefied coditios, ad that methods may, therefore, always referece the objects without the risk of makig iaccurate presumptios. Class ivariats are established durig costructio ad costatly maitaied betwee calls to public methods. Temporary breakig of class ivariace betwee private method calls is possible, although ot ecouraged. Defiig class ivariats ca help programmers ad testers to catch more bugs durig software testig. Desigig A Perso Class: Istace Variables A simple Perso class could cotai istace variables represetig a perso's ame, the date o which they were bor, ad the date o which they died These istace variables would all be class types: ame of type Strig, ad two dates of type Date As a first lie of defece for privacy, each of the istace variables would be declared private public class Perso { private Strig ame; private Date bor; private Date died; //ull is still alive... 3 Copyright 2017 Pearso Ltd. All rights reserved. 4 Desigig a Perso Class: Costructor A Perso Class Costructor I order to exist, a perso must have (at least) a ame ad a birth date Therefore, it would make o sese to have a o-argumet Perso class costructor A perso who is still alive does ot yet have a date of death Therefore, the Perso class costructor will eed to be able to deal with a ull value for date of death A perso who has died must have had a birth date that preceded his or her date of death Therefore, whe both dates are provided, they will eed to be checked for cosistecy public Perso(Strig iitialname, Date birthdate, Date deathdate){ if (cosistet(birthdate, deathdate)){ ame = iitialname; bor = ew Date(birthDate); if (deathdate == ull) died = ull; Copyright 2017 Pearso Ltd. All rights reserved. 5 Copyright 2017 Pearso Ltd. All rights reserved. { died = ew Date(deathDate); System.out.pritl("Icosistet dates."); System.exit(0); 6
Desigig a Perso Class: the Class Ivariat Desigig a Perso Class: the Class Ivariat Ivariat = Αναλλοίωτος περιορισμός Class ivariat: A statemet that is always true for every object of the class A class ivariat ca help to defie a class i a cosistet ad orgaized way For the Perso class, the followig should always be true: A object of the class Perso has a date of birth (which is ot ull), ad if the object has a date of death, the the date of death is equal to or later tha the date of birth Checkig the Perso class cofirms that this is true of every object created by a costructor, ad all the other methods (e.g., the private method cosistet) preserve the truth of this statemet /** Class ivariat: A Perso always has a date of birth, ad if the Perso has a date of death, the the date of death is equal to or later tha the date of birth. To be cosistet, birthdate must ot be ull. If there is o date of death (deathdate == ull), that is cosistet with ay birthdate. Otherwise, the birthdate must come before or be equal to the deathdate. */ private static boolea cosistet(date birthdate, Date deathdate){ if (birthdate == ull) retur false; if (deathdate == ull) retur true; retur (birthdate.precedes(deathdate) birthdate.equals(deathdate)); 7 Copyright 2017 Pearso Ltd. All rights reserved. 8 public boolea precedes(date otherdate) { retur ((year < otherdate.year) (year == otherdate.year && getmoth() < otherdate.getmoth()) (year == otherdate.year && moth.equals(otherdate.moth) && day < otherdate.day)); public boolea equals(date otherdate) { if (otherdate == ull) retur false; retur ((moth.equals(otherdate.moth)) && (day == otherdate.day) && (year == otherdate.year)); Desigig a Perso Class: the equals Method public boolea equals(perso otherperso){ if (otherperso == ull) retur false; retur (ame.equals(otherperso.ame) && bor.equals(otherperso.bor) && datesmatch(died, otherperso.died)); 9 Copyright 2017 Pearso Ltd. All rights reserved. 10 Perso Class: the equals ad datesmatch Methods The defiitio of equals for the class Perso icludes a ivocatio of equals for the class Strig, ad a ivocatio of the method equals for the class Date Java determies which equals method is beig ivoked from the type of its callig object Also ote that the died istace variables are compared usig the datesmatch method istead of the equals method. WHY?? datesmatch(died, otherperso.died) Desigig a Perso Class: the matchdate Method /** To match date1 ad date2 must either be the same date or both be ull. */ private static boolea datesmatch(date date1, Date date2){ if (date1 == ull) retur (date2 == ull); if (date2 == ull) //&& date1!= ull retur false; // both dates are ot ull. retur(date1.equals(date2)); Copyright 2017 Pearso Ltd. All rights reserved. 11 Copyright 2017 Pearso Ltd. All rights reserved. 12
Desigig a Perso Class: the tostrig Method Περίγραμμα The Perso class tostrig method icludes ivocatios of the Date class tostrig method: Aναλλοίωτοι Περιορισμοί Παραβίαση ιδιωτικότητας, Κατασκευαστές αντιγραφείς (copy costructors). Μεταλλάξιμες και μη μεταλλάξιμες κλάσεις public Strig tostrig( ) { Strig diedstrig; if (died == ull) diedstrig = ""; //Empty strig diedstrig = died.tostrig( ); Βιβλιοθήκες Java και Javadoc Επίλυση Υπολογιστικών Προβλημάτων retur (ame + ", " + bor + "-" + diedstrig); Copyright 2017 Pearso Ltd. All rights reserved. 13 14 Usig ad Misusig Refereces Whe writig a program, it is very importat to isure that private istace variables remai truly private Privacy leaks (παραβίαση ιδιωτικότητας) How?? For a primitive type istace variable, just addig the private modifier to its declaratio should isure that there will be o privacy leaks (παραβίαση ιδιωτικότητας) For a class type istace variable, however, addig the private modifier aloe is ot sufficiet 15 16 Copy Costructors A copy costructor is a costructor with a sigle argumet of the same type as the class The copy costructor should create a object that is a separate, idepedet object, but with the istace variables set so that it is a exact copy of the argumet object Note how, i the Date copy costructor, the values of all of the primitive type private istace variables are merely copied Copy Costructor for a Class with Primitive Type Istace Variables public Date(Date adate) { if (adate == ull) { //Not a real date. System.out.pritl("Fatal Error."); System.exit(0); moth = adate.moth; day = adate.day; year = adate.year; Copyright 2017 Pearso Ltd. All rights reserved. 17 Copyright 2017 Pearso Ltd. All rights reserved. 18
Copy Costructor for a Class with Class Type Istace Variables Ulike the Date class, the Perso class cotais three class type istace variables If the bor ad died class type istace variables for the ew Perso object were merely copied, the they would simply reame the bor ad died variables from the origial Perso object bor = origial.bor //dagerous died = origial.died //dagerous This would ot create a idepedet copy of the origial object Copy Costructor for a Class with Class Type Istace Variables The actual copy costructor for the Perso class is a "safe" versio that creates completely ew ad idepedet copies of bor ad died, ad therefore, a completely ew ad idepedet copy of the origial Perso object For example: bor = ew Date(origial.bor); Note that i order to defie a correct copy costructor for a class that has class type istace variables, copy costructors must already be defied for the istace variables' classes Copyright 2017 Pearso Ltd. All rights reserved. 19 Copyright 2017 Pearso Ltd. All rights reserved. 20 Copy Costructor for a Class with Class Type Istace Variables public Perso(Perso origial) { if (origial == ull) { System.out.pritl("Fatal error."); System.exit(0); ame = origial.ame; bor = ew Date(origial.bor); if (origial.died == ull) died = ull; died = ew Date(origial.died); Pitfall: Privacy Leaks The previously illustrated examples from the Perso class show how a icorrect defiitio of a costructor ca result i a privacy leak A similar problem ca occur with icorrectly defied mutator or accessor methods For example: public Date getbirthdate(){ retur bor; //dagerous Istead of: public Date getbirthdate(){ retur ew Date(bor); //correct Copyright 2017 Pearso Ltd. All rights reserved. 21 Copyright 2017 Pearso Ltd. All rights reserved. 22 Περίγραμμα Aναλλοίωτοι Περιορισμοί Παραβίαση ιδιωτικότητας, Κατασκευαστές αντιγραφείς (copy costructors). Μεταλλάξιμες και μη μεταλλάξιμες κλάσεις Βιβλιοθήκες Java και Javadoc Επίλυση Υπολογιστικών Προβλημάτων Mutable ad Immutable Classes The accessor method getname from the Perso class appears to cotradict the rules for avoidig privacy leaks: public Strig getname(){ retur ame; //Is't this dagerous? Although it appears the same as some of the previous examples, it is ot: The class Strig cotais o mutator methods that ca chage ay of the data i a Strig object 23 Copyright 2017 Pearso Ltd. All rights reserved. 24
Mutable ad Immutable Classes A class that cotais o methods (other tha costructors) that chage ay of the data i a object of the class is called a immutable class (μη μεταλλάξιμη κλάση) Objects of such a class are called immutable objects It is perfectly safe to retur a referece to a immutable object because the object caot be chaged i ay way The Strig class is a immutable class Mutable ad Immutable Classes A class that cotais public mutator methods or other public methods that ca chage the data i its objects is called a mutable class (μεταλλάξιμη κλάση), ad its objects are called mutable objects (μεταλλάξιμα αντικείμενα) Never write a method that returs a mutable object Istead, use a copy costructor to retur a referece to a completely idepedet copy of the mutable object Copyright 2017 Pearso Ltd. All rights reserved. 25 Copyright 2017 Pearso Ltd. All rights reserved. 26 Deep Copy Versus Shallow Copy A deep copy (βαθύ αντίγραφο) of a object is a copy that has o refereces i commo with the origial Οe Exceptio: Refereces to immutable objects are allowed to be shared Ay copy that is ot a deep copy is called a shallow copy (επιφανειακό αντίγραφο). This type of copy ca cause dagerous privacy leaks i a program Περίγραμμα Aναλλοίωτοι Περιορισμοί Παραβίαση ιδιωτικότητας, Κατασκευαστές αντιγραφείς (copy costructors). Μεταλλάξιμες και μη μεταλλάξιμες κλάσεις Βιβλιοθήκες Java και Javadoc Επίλυση Υπολογιστικών Προβλημάτων Copyright 2017 Pearso Ltd. All rights reserved. 27 28 Packages ad Import Statemets Βιβλιοθήκες Java και Επαναχρησιμοποίηση Κώδικα (Java packages ad code re-use) Java uses packages to form libraries of classes A package is a group of classes that have bee placed i a directory or folder, ad that ca be used i ay program that icludes a import statemet that ames the package The import statemet must be located at the begiig of the program file: Oly blak lies, commets, ad package statemets may precede it The program ca be i a differet directory from the package 29 Copyright 2017 Pearso Ltd. All rights reserved. 30
Import Statemets We have already used import statemets to iclude some predefied packages i Java, such as Scaer from the java.util package import java.util.scaer; It is possible to make all the classes i a package available istead of just oe class: Note that there is o additioal overhead for importig the etire package The package Statemet To make a package, group all the classes together ito a sigle directory (folder), ad add the followig package statemet to the begiig of each class file: package package_ame; Oly the.class files must be i the directory or folder, the.java files are optioal Oly blak lies ad commets may precede the package statemet If there are both import ad package statemets, the package statemet must precede ay import statemets Copyright 2017 Pearso Ltd. All rights reserved. 31 Copyright 2017 Pearso Ltd. All rights reserved. 32 The Package java.lag Package Names ad Directories The package java.lag cotais the classes that are fudametal to Java programmig It is imported automatically, so o import statemet is eeded Classes made available by java.lag iclude Math, Strig, ad the wrapper classes A package ame is the path ame for the directory or subdirectories that cotai the package classes Java eeds two thigs to fid the directory for a package: the ame of the package ad the value of the CLASSPATH variable The CLASSPATH eviromet variable is similar to the PATH variable, ad is set i the same way for a give operatig system The CLASSPATH variable is set equal to the list of directories (icludig the curret directory, ".") i which Java will look for packages o a particular computer Java searches this list of directories i order, ad uses the first directory o the list i which the package is foud 33 Copyright 2017 Pearso Ltd. All rights reserved. 34 A Package Name Pitfall: Subdirectories Are Not Automatically Imported Whe a package is stored i a subdirectory of the directory cotaiig aother package, importig the eclosig package does ot import the subdirectory package The import statemet: import utilities.umericstuff.*; imports the utilities.umericstuff package oly The import statemets: import utilities.umericstuff.*; import utilities.umericstuff.statistical.*; import both the utilities.umericstuff ad utilities.umericstuff.statistical packages Copyright 2017 Pearso Ltd. All rights reserved. 35 Copyright 2017 Pearso Ltd. All rights reserved. 36
The Default Package All the classes i the curret directory belog to a uamed package called the default package As log as the curret directory (.) is part of the CLASSPATH variable, all the classes i the default package are automatically available to a program Pitfall: Not Icludig the Curret Directory i Your Class Path If the CLASSPATH variable is set, the curret directory must be icluded as oe of the alteratives Otherwise, Java may ot eve be able to fid the.class files for the program itself If the CLASSPATH variable is ot set, the all the class files for a program must be put i the curret directory Copyright 2017 Pearso Ltd. All rights reserved. 37 Copyright 2017 Pearso Ltd. All rights reserved. 38 Specifyig a Class Path Whe You Compile The class path ca be maually specified whe a class is compiled Just add classpath followed by the desired class path This will compile the class, overridig ay previous CLASSPATH settig You should use the classpath optio agai whe the class is ru Ένα πρόγραμμα σε Java // Property.java public class Property { public static void mai(strig[] args) { Caledar caledar = Caledar.getIstace(); System.out.pritl(caledar.getTime()); Properties p = System.getProperties(); p.list(system.out); System.out.pritl("-- Memory usage:"); Rutime rt = Rutime.getRutime(); System.out.pritl("Total Memory = "+ rt.totalmemory() + " Free Memory = " + rt.freememory()); 39 Μ. Δικαιάκος, EΠΛ233 Μ. Δικαιάκος, EΠΛ233 41 Μ. Δικαιάκος, EΠΛ233 42
Διαχείριση Ονοµάτων Πώς αποφεύγουµε συγκρούσεις ανάµεσα σε δύο ονόµατα (µεθόδων, µεταβλητών, πεδίων δεδοµένων...); Μ. Δικαιάκος, EΠΛ233 43 44 Ορατότητα Ονομάτων (ame visibility) Αποφυγή συγκρούσεων ονομάτων: Μέθοδοι και πεδία δεδομένων είναι πάντοτε φωλιασμένα σε κλάσεις και καλούνται μέσω του ονόματος αντικειμένων. Επομένως, δεν υπάρχει περίπτωση σύγκρουσης με ονόματα μεθόδων ή πεδίων δεδομένων άλλων κλάσεων. Τι συμβαίνει με τα ονόματα των κλάσεων; Η JAVA εισάγει μια σύμβαση σύμφωνα με την οποία κάθε αρχείο Java αντιστοιχεί αυτόματα σε έναν δικό του χώρο ονομάτων (ame space) και κάθε κλάση μέσα στο αρχείο έχει αυτόματα μια μοναδική ταυτότητα (idetifier). Για την αποφυγή συγκρούσεων ανάμεσα σε ομώνυμες κλάσεις διαφορετικών προγραμματιστών, κάθε προγραμματιστής μπορεί να επιδιώκει την χρήση μοναδικών ονομάτων. Π.χ.: cy.ac.ucy.cs.mdd.utils l Κανόνες προτεραιότητας ονομάτων Πού ορίζεται η κλάση Radom; public class Test { public static void mai(strig[] args) { Radom rad = ew Radom(); it j = rad.extit() % 100; l Τι συμβαίνει στο ακόλουθο; public class Radom { it extit() { retur 0; public class Test { public static void mai(strig[] args) { Radom rad = ew Radom(); it j = rad.extit() % 100; Μ. Δικαιάκος, EΠΛ233 45 Μ. Δικαιάκος, EΠΛ233 46 Ονοματολογία Κλάσεων και Μεθόδων class Radom { it extit() { retur 0; public class Test { public static void mai(strig[] args) { java.util.radom rad = ew java.util.radom(); it j = rad.extit() % 100; javadoc revisited Ulike a laguage such as C++, Java places both the iterface ad the implemetatio of a class i the same file However, Java has a program called javadoc that automatically extracts the iterface from a class defiitio ad produces documetatio This iformatio is preseted i HTML format, ad ca be viewed with a Web browser If a class is correctly commeted, a programmer eed oly refer to this API (Applicatio Programmig Iterface) documetatio i order to use the class javadoc ca obtai documetatio for aythig from a sigle class to a etire package Μ. Δικαιάκος, EΠΛ233 47 48
Commetig Classes for javadoc The javadoc program extracts class headigs, the headigs for some commets, ad headigs for all public methods, istace variables, ad static variables I the ormal default mode, o method bodies or private items are extracted To extract a commet, the followig must be true: The commet must immediately precede a public class or method defiitio, or some other public item The commet must be a block commet, ad the opeig /* must cotai a extra * ( /**... */ ) Note: Extra optios would have to be set i order to extract lie commets ( // ) ad private items Commetig Classes for javadoc I additio to ay geeral iformatio, the commet precedig a public method defiitio should iclude descriptios of parameters, ay value retured, ad ay exceptios that might be throw This type of iformatio is preceded by the @ symbol ad is called a @ tag @ tags come after ay geeral commet, ad each oe is o a lie by itself /** Geeral Commets about the method... @param aparameter Descriptio of aparameter @retur What is retured... */ 49 50 @ Tags @tags should be placed i the order foud below If there are multiple parameters, each should have its ow @param o a separate lie, ad each should be listed accordig to its left-toright order o the parameter list If there are multiple authors, each should have its ow @author o a separate lie @param Parameter_Name Parameter_Descriptio @retur Descriptio_Of_Value_Retured @throws Exceptio_Type Explaatio @deprecated @see Package_Name.Class_Name @author Author @versio Versio_Iformatio Ruig javadoc To ru javadoc o a package, give the followig commad: javadoc d Documetatio_Directory Package_Name The HTML documets produced will be placed i the Documetatio_Directory If the d ad Documetatio_Directory are omitted, javadoc will create suitable directories for the documetatio To ru javadoc o a sigle class, give the followig commad from the directory cotaiig the class file: javadoc ClassName.java To ru javadoc o all the classes i a directory, give the followig commad istead: javadoc *.java 51 52 Optios for javadoc Copyright 2017 Pearso Ltd. All rights reserved. 53