Notes on Organzng Java Code: Packages, Vsblty, and Scope CS 112 Wayne Snyder Java programmng n large measure s a process of defnng enttes (.e., packages, classes, methods, or felds) by name and then usng those names n varous contexts, and the rules for how we go about ths determne how we organze our code. In ths set of notes, we wll consder these rules n detal; n partcular, we want to understand, for each entty, the followng: 1) What s the scope of the defnton (the locatons n code that the defnton can be used) and what mechansms exst for extendng or modfyng that scope? 2) How do we refer to the entty,.e., what s the syntax of the name when t s used? 3) What happens f we have multple defntons of a name? 4) What s the lfetme of the defnton,.e., when does t begn to be vsble and when does ts vsblty end? The purpose of ths study s frst to understand the detals of how we use class and class member defntons as we wrte lnes of Java code, but secondly we want to understand how these rules allow us to structure large Java projects followng the object- orented phlosophy. Packages and the fle system The envronment n whch you run Java on your computer conssts of fles of Java code (endng n.java) contanng class defntons, compled Java classes (fles endng n.class), and rules for how a partcular pece of code wll execute; most of these rules nvolve how to name classes and how to refer to one class from another class. In ths set of notes we wll consder broadly how code s organzed on your computer, focussng n partcular on the noton of a package. The man folder where you store your Java code s sometmes referred to as the workspace, and t s organzed herarchcally as follows: Workspace Packages (subfolders) Fles Classes Members: felds, methods and nested classes
Your workspace (or workng drectory) may contan subfolders to organze your Java code, and these are any number of packages, and packages are typcally organzed n a herarchcal structure (the dotted names correspond to the folder structure) but each package s a separate entty and so ths herarchy s just for keepng your fles organzed n the fle system: there s no concept of a subpackage and ths herarchy has no effect anythng we dscuss n these notes. If you don t specfy a package when you create a class, t s put n the default or nameless package, as you can see wth the class TestDefault below. For example, consder the followng fles and folders n our workspace, whch we wll use as a runnng example: Workspace TestDefault.java alpha TestAlpha.java beta TestBeta.java one Test1.java one.two Test12.java one.two.three Test123.java (where the folders are underlned). Ths mght appear n your Mac as follows:
Packages: Makng a fle part of a package A.java fle contans one or more class defntons, and to be n a package t must be n the approprate folder, as descrbed above, and also must contan a package statement, e.g., f Test1.java s n package one, t must begn wth the lne: package one; and f Test123.java s n package one.two.three, t begns wth the lne: package one.two.three; A fle wth no package declaraton s n the default package. Packages: Usng classes n the same package When you want to refer to classes n the same package, you smply use ther smple names (you have doubtless been dong ths all along for fles n the default package). However, when you want to use a publc class n the same project, but n a dfferent package, you have bascally two choces: 1) You can use the full name wth the package and the class name. For example, n the fgure, to declare a Test12 class nstance from package one.two from nsde Test123, you can wrte one.two.test12 t2; Ths wll work from any class n the project, ncludng classes n the default package. 1 2) You can mport the class and then smply use the name of the class; for example, to create an nstance of Test1 nsde Test123, you could wrte the followng (as seen n the fgure): mport one.test1;.. Test1 t = new Test1(); To mport all the publc classes n a package, you can use a wldcard n place of the class name, e.g., we could have mported all publc classes n package one usng: mport one.*; (snce there was only one class n any case, these would be equvalent). Important note: When you mport wth the wldcard *, you get only the classes n that package/folder and no others; e.g., when you mport one.* you do not 1 However, there s no way to refer to classes n the default package from a dfferent package, whch s a good reason to avod the default package!
automatcally get the classes n one.two and one.two.three. You have to lst all the packages separately you want to mport. Agan, the only reason for the herarchcal organzaton of packages s to organze your folders- - - there s no effect on the process of fndng defntons of names. Multple defntons of a class and the buldpath When you comple your Java code, the comple has to fnd the classes that you have referred to n your code, and to do ths, t uses the buldpath, whch s smply a lst of folders to look n, one after the other, for classes. The frst place t looks s n your workspace, and the second place s n the Java lbrary that came wth your compler (ths s where basc thngs lke the Math class are stored); you can change the buldpath f you lke, but that s outsde the scope of these notes. What happens when you have two classes wth the same name? The rule s very smple: a class may not be redefned wthn ts vsblty, wth the excepton of multple defntons n packages that are lsted on the buldpath, n whch case the Java compler wll use the frst defnton that t comes to n gong down the buldpath. Thus, you may redefne the class Math and provde your own defnton of the method pow(), and put t n your buldpath before the JRE, and ths s the one that wll be used by default. In every other case, the Java compler wll complan f you have multple defntons for a name (as you have no doubt experenced!). Access modfers: publc, prvate, and package access Now we can understand the vsblty of classes defned n fles n a package. There are two possbltes: 1) A class s declared as publc: there are no restrctons on ts vsblty; t can be used by any other class that can fnd t (e.g., n the same package, or n another package that has the approprate buldpath). 2) A class s declared as protected: ths has to do wth subclasses, and wll be dealt wth late n the course when we dscuss nhertance. 3) A class s declared wthout ether of these access modfers: n ths case, the default s package access, whch means that t s vsble only n ts own package. The class can not be mported or named by ts full package name n another package, and no modfcaton of the buldpath wll make t accessble from another project; for example, n the fgure f we removed the publc modfers from the defntons of Test1, Test12, or TestAlpha, we would get a not vsble error n Test123. For members (.e., felds, methods, and nner classes), we have four possbltes: 1) The member s declared as publc: t s vsble wherever the class s vsble; 2) The member s delcared as protected: agan, we shall deal wth ths later;
3) The member s declared as prvate, and t s vsble nsde the class only, and nvsble outsde the curly braces of the class; 4) The member s declared wthout a modfer, and has package access; ths means t s vsble nsde the package only. How to organze your classes n fles Fnally, there s the matter of how classes are arranged n the fles. Recall that a package s really a folder whch contans fles whch contan defntons of classes. There can be more than one class defnton per fle, but we have the followng restrctons on publc classes: 1) There can be at most one publc class per fle; 2) A publc class must have the same name as the fle (wth the.java suffx); and 3) Man methods can only occur n publc classes. It s a good dea to put any substantal class n ts own fle, and to have multple classes n a fle only when they are very closely related to each other; f they are only used n one class n that fle, then they should be made nto nner classes. Vsblty of class felds and local varables [Optonal] We wll now consder the ssue of vsblty n the case of local varables, felds, and then the combnaton of these two. Local Varables n Methods The rule for local varables defned nsde methods s actually qute smple: the scope of a local varable defnton s from the pont of the defnton to the end of the closest enclosng par of curly braces, and you may not redefne a varable wthn ts scope. Defntons nsde the headng of for loops, and parameters n methods, have scope from the pont of defnton to the end of the curly braces enclosng the loop or method. For example, here s the scope of the sx local varables n a slly method; note carefully that j and k are both defned twce, but not redefned nsde ther scope, so there s no problem (e.g., the two j s are dfferent varables): statc vod slly(nt m) { m nt = 4; m m for(nt j=0; j<10; j++) { m j nt k = 2; m j k k = k + + j; m j k m m for(nt j=0; j<20; j++) { m j nt k = 9; m j k k = k + - j; m j k
m m A varable must be ntalzed before ts frst use (there s no default ntalzaton for local varables). Felds n Classes The stuaton for felds s somewhat dfferent, snce the felds are defntons of the members avalable n a class, and are not so obvously part of an executable regon of code. Here the rule s: a feld defnton has scope over the entre class, but may be redefned as part of a method or nested class; ntalzatons (f they are done n the defnton, and not n the constructor) take place n the order of the felds n the class. Although the usual practce s to provde explct ntalzaton values n the constructor, we may do t n the defnton n the class tself, n whch case the ntalzatons take place n the order of the felds (as f they were executable statements n a method). Thus, a method may refer to a feld that s defned anywhere n the class, but feld ntalzaton may only use the defntons above t n the lst of felds. Felds are ntalzed to 0 or null or false by default. For example, n the followng class, n s ntalzed to 0, m would be ntalzed to 4, k to 4, and p to 5; the dagram shows the scope of each of the felds, and the underlned names show the scope of the sequental ntalzaton. Thus, f we were to change the ntalzaton of k = n + p t would be an error, snce the defnton of p occurs below the defnton of k. publc class TestDefault { nt n; n m k p nt m = 4; n m k p n m k p nt sllymethod(nt q) { n m k p q return q + n + m + k; n m k p q n m k p n m k p nt k = n + m; n m k p nt p = m + 1; n m k p We saw above that we may not redefne a local varable n ts scope. However, t s possble to redefne a feld name nsde ts scope, by reusng the name as a local varable or a feld n a nested class. Ths s sometmes useful, snce the name may be descrptve n a way that s dentcal n two contexts (e.g.,, counter, next ). Reusng common names may be easer and less confusng than comng up wth new names. The basc dea when reusng feld names, or when mxng felds and local varables, s that a use of a name refers to the closest enclosng defnton. For example, n the followng (contrved) example, there s a feld whch s superceded
by a local varable n a method and a feld nsde an nner class, creatng two holes n the outermost defnton of ; the nested class feld s n turn superceded by a local varable of the same name. Each column of s showng the scope s a dstnct varable: publc class TestDefault { nt = 1; // feld class TestIt { nt = 2; // feld // here == 2 nt testitmethod() { nt = 3; // local varable // here == 3 return ; nt testdefaultmethod() { nt = 4; // local varable // here == 4 TestIt t = new TestIt(); return ; // prnts 4 //return ths.; prnts 1 //return t.; prnts 2 //return t.testitmethod(); prnts 3 publc statc vod man (Strng [] cmd) { TestDefault d = new TestDefault(); System.out.prntln(d.testDefaultMethod()); A sgnfcant ssue when redefnton s allowed s how we may refer to the varous defntons. Of course, the default s to use the closest enclosng defnton. However, we can also refer n some cases to other defntons, as shown n the comments attached to the varous alternatve return statements n testmethod() above: 1) return yelds 4 usng the default rule; 2) return ths. yelds 1, as the keyword ths refers to the current nstance of the class where ths method was defned (just go outward untl you ht a defnton of a feld ); 3) return t. yelds 2, as ths s a feld defned nsde t, whch s an nstance of TestIt; and 4) return t.testitmethod() yelds 3, as the method returns the value of ts local varable. Note that you may not refer to the feld n TestDefault from wthn the scope of the feld n TestIt, snce ths would refer to ts own current nstance; we wll see later n the course that ths wll be possble when usng statc classes. [End Optonal]
Lfetme of Defntons: Statc vs Instance Felds and Methods Up to ths pont, we have not engaged wth our fourth queston wth whch we began,.e., when do defntons come nto beng and when do they end? In Java ths queston s very smply answered: 1) When a member of a class s declared wth the statc keyword, there s exactly one nstance of that member, whch s created automatcally before the program begns to run, and exsts untl the program termnates. 2) When member of a class s declared wthout the statc keyword, then an nstance of that member s created by the constructor for each nstance of the class that s created; ts lfetme s the lfetme of the nstance. In addton to the temporal ssue of lfetme, t s very mportant to note that statc members have only one nstance, and although all nstances of the class may use t, they all use that sngle nstance. Statc Felds The best way to see how ths works s wth an example: the followng class represents a lne and contans a statc feld countng how many nstances have been created: class Lne { statc nt count = 0; // keeps track of how many lnes exst publc nt order; // when was ths one created publc double x, double y; publc Lne(double x, double y) { order = ++count; ths.x = x; ths.y = y; publc class LneTest { publc statc vod man(strng[] args) { Lne l1 = new Lne(0.0, 0.0); Lne l2 = new Lne(2.3, 3.4); // Now l1.count == 2 and l2.order == 2 Lne l3 = new Lne(1.2, 6.7); // Now l1.count == 3 and l2.order == 2 We may llustrate ths as follows, where we show a statc regon of memory whch exsts durng the entre program lfetme, and a dynamc regon of memory where (possbly multple ) nstances of a class are created and (perhaps) destroyed:
Statc Memory Dynamc Memory Lne l1 l2 l3 count: 3 order: 1 x: 0.0 y: 0.0 order: 2 x: 2.3 y: 3.4 order: 3 x: 1.2 y: 6.7 When referrng to members of classes, t s very mportant to realze that there are multple nstances of non- statc members (one for each class nstances), and that these must be referred ether locally nsde the methods of the class nstances, or from outsde through the name of the nstance, e.g., l1.order, l2.x, etc. A statc member may be referred n the same way as a non- statc member BUT ALSO through the name of the class, e.g., Lne.count. Note that nstance felds may be ntalzed by the constructor, but statc felds have no explct constructor, and must be ntalzed n the class defnton tself (as we see wth count above). Statc Methods We may also defne statc methods, n whch case there s exactly one nstance of the method, wth all ts local varables (whch are themselves statc); for example, man() s always a statc method. Agan, any nstance may refer to a statc method by ts smple name nsde the class, by the nstance from outsde the class, and through the name of the class. However, there s an mportant restrcton to keep n mnd wth statc methods: a statc method may not refer to a non- statc member except through the name of the nstance, because there may be no such nstances, or multple nstances. A example wll make ths clear. Here s the Lne class wth a non- statc method whch calculates the length of the lne: class Lne {
statc nt count = 0; // keeps track of how many lnes exst publc nt order; // when was ths one created publc double x, double y; publc Lne(double x, double y) { order = ++count; ths.x = x; ths.y = y; double length() { return Math.sqrt(x*x + y*y); // sqrt s a statc method of class Math! publc class LneTest { publc statc vod man(strng[] args) { Lne l1 = new Lne(0.0, 0.0); Lne l2 = new Lne(2.3, 3.4); // Now l2.length() would return 4.104875150354758 We could call length() nsde another method of Lne, or call t through the name of ts nstance. But what would happen f we made length() statc? statc double length() { return Math.sqrt(x*x + y*y); The answer s that we would get four comple- tme errors Can not make a statc reference to the non- statc feld, one for each occurrence of x and y. Clearly, ths defnton makes no sense: whch x and y are ntended? However, a statc method statc nt getcount() { return count; would generate no errors. We may magne the code for statc methods as lvng n the statc memory nstance of the class, and the non- statc methods as lvng n each nstance, and so a method may refer only to felds n ts own nstance: Statc Memory Dynamc Memory Lne l1 l2 l3 count: 3 nt getcount() { order: 1 x: 0.0 y: 0.0 double length() {. order: 2 x: 2.3 y: 3.4 double length() {. order: 3 x: 1.2 y: 6.7 double length() {.
Why are statc felds and methods useful? Frstly, some utlty methods, such as those n the Math class, have no need for any local data, and hence the class s just a contaner for a bunch of commonly- used functons; t s more effcent to have only one nstance of ths class rather than havng to create an nstance every tme we want to use the Math methods. Second, sometmes, as wth the feld count above, t s useful to have some global nformaton that all class nstances can use. Summary 1) The nformaton herarchy s workspace : projects : packages : fles : classes : members. We may have a herarchy of nested classes as felds nsde classes or as local varables n methods. 2) Packages are stored n a herarchcal fle system n ther projects correspondng to the structure of ther (dot- separated) compound names. 3) Fles can contan any number of classes, but at most one publc class, whch has to have the same name as the fle; publc statc man methods can only occur n such publc classes. 4) Publc enttes are vsble anywhere ther defner s, prvate enttes are vsble only n ther own class, and the default vsblty s nsde one s own package. 5) Classes can refer to classes n the same package by ther smple names, can refer to classes n the same project but dfferent packages by mportng the package or prefxng the name of the package, and projects can refer to each other by extendng the buldpath. 6) Classes may not be redefned wthn ther vsblty, wth the excepton of multple defntons exstng on the buldpath, n whch case the compler uses the frst defnton encountered. 7) The scope of a local varable s from the pont of defnton to the end of the closest enclosng rght brace, or, n the case of method or loop parameters, to the end of the loop or method; local varables may not be redefned wthn ther scope. 8) The scope of a feld n a class s the entre class (except for holes- n- scope produced by redefntons), but ntalzatons take place n the feld order. 9) Names of felds may be redefned by local varables n methods, or by felds n nested classes; one may refer to felds outsde of ther scope only by usng the usual rules for referrng to felds n nstances of classes, the keyword ths beng used to refer to the current nstance of the closest enclosng class. 10) Statc felds have exactly one nstance, whch exsts for the entre runnng tme of the program, and whch are accessble from nsde any nstance, and from outsde through an nstance name, or through the name of the class. Statc methods may be referred to analogously, but may themselves only refer to statc felds.