Chap 1 Declarations and Acces Control Update

  • Upload
    tayssir

  • View
    227

  • Download
    0

Embed Size (px)

Citation preview

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    1/26

    Chapitre 1

    Declarationsand Access Control

    MohamedRomdhani

    INSAT

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    2/26

    310-065 C apitre 1

    2M. Romdhani, Fvrier 2009

    Plan

    Identifiers and JavaBeans Legal Idenfiers Sun's Java Code Conventions JavaBeans Naming Standards

    Declare Classes

    Source File Declaration Rules Class Declarations and Modifiers Class Access Oter !Nonaccess" Class Modifiers

    Declare Interfaces

    Declaring an Interface Declaring Interface Constants

    Declare Class Members

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    3/26

    310-065 C apitre 1

    3M. Romdhani, Fvrier 2009

    Identifiers and JavaBeans

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    4/26

    310-065 C apitre 1

    4M. Romdhani, Fvrier 2009

    Legal Idenfiers

    Identifiers must start with a letter, a currency character ($), or aconnectin character such as the underscore ( ! )"

    Identifiers cannot start #it a num$er %

    After te first caracter& identifiers can contain an com$ination of letters&currenc caracters& connecting caracters& or num$ers(

    In )ractice& tere is no limit to te num$er of caracters an identifier can contain(

    Identifiers in Java are case#sensitive foo and %oo are two differentidentifiers"

    &ou can't use a Java eyword as an identifier" Java * +e#ords

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    5/26

    310-065 C apitre 1

    5M. Romdhani, Fvrier 2009

    Legal Identifiers (!a"ples#

    *am+les of some leal identifiers

    int ,a-

    int .c-

    int ,,,,,,/,#-

    int ,.-

    int tis,is,a,ver,detailed,name,for,an,identifier-

    he followin are illeal (it's your -ob to reconi.e why)

    int $0-

    int 1d-

    int e2-

    int (f-

    int 3g-

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    6/26

    310-065 C apitre 1

    $M. Romdhani, Fvrier 2009

    %&n's Java Code Conventions

    Classes and interfaces

    he first letter should be ca+itali.ed& and if several #ords are lin4ed togeter toform te name& te first letter of te inner #ords sould $e u))ercase !a format tat'ssometimes called 56ascalCase5"( For classes& te names sould t)icall $e nouns(

    For e7am)le0 Dog & Account & 6rint8riter

    For interfaces& te names sould t)icall $e ad9ectives li4e 0Runna$le Seriali:a$le

    Methods

    he first letter should be lowercase& and ten normal camelCase rules sould $eused( In addition& te names sould t)icall $e ver$1noun )airs(

    For e7am)le0 getBalance!" doCalculation!"& setCustomerName!"

    /ariables

    Li4e metods& te camelCase format sould $e used& startin with a lowercaseletter( Sun recommends sort& meaningful names& #ic sounds good to us( Some e7am)les0 $utton8idt accountBalance mString

    Constants

    Java constants are created $ mar4ing varia$les static and final( ;e sould $enamed using u++ercase letters#it underscore caracters as se)arators0 MIN,,

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    7/26

    310-065 C apitre 1

    M. Romdhani, Fvrier 2009

    JavaBeans %tandards

    %irst, JavaBeans are Java classes that have properties" For our )ur)oses& tin4 of )ro)erties as )rivate instance varia$les(

    ;e metods tat cange a )ro)ert's value are called settermetods& and te metods tatretrieve a )ro)ert's value are called gettermetods(

    JavaBean 0ro+erty 1amin Rules

    If te )ro)ert is not a $oolean& the etter method's +refi* must be get(

    If te )ro)ert is a $oolean& te getter metod's )refi7 is eiter get or is( For e7am)le&getSto))ed!" or isSto))ed!" are $ot valid JavaBeans names for a $oolean )ro)ert(

    he setter method's +refi* must be set(

    ;o com)lete te name of a getter or setter metod& cange te first letter of te)ro)ert name to u))ercase& and ten a))end it to te a))ro)riate )refi7 !get& is&or set"(

    Setter metod signatures must $e mar4ed )u$lic& #it a void return t)e and anargument tat re)resents te )ro)ert t)e(

    >etter metod signatures must $e mar4ed )u$lic& ta4e no arguments& and ave areturn t)e tat matces te argument t)e of te setter metod for tat )ro)ert(

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    8/26

    310-065 C apitre 1

    )M. Romdhani, Fvrier 2009

    JavaBeans %tandards

    the JavaBean s+ec su++orts events, which allow com+onents to notify

    each other when somethin ha++ens" ;e event model is often used in >?I a))lications #en an event li4e a mouse clic4 is

    multicast to man oter o$9ects tat ma ave tings to do #en te mouse clic4 occurs(

    JavaBean 2istener 1amin Rules

    Listener metod names used to 5register5 a listener #it an event source must

    use the +refi* add& follo#ed $ te listener t)e( For e7am)le& addActionListener!" is a valid name for a metod tat an

    event source #ill ave to allo# oters to register for Action events(

    Listener metod names used to remove !5unregister5" a listener must use the+refi* remove& follo#ed $ te listener t)e !using te same rules as teregistration add metod"(

    ;e t)e of listener to $e added or removed must $e )assed as te argument tote metod(

    =7am)les of valid JavaBean metod signatures are

    )u$lic void addMListener!MListener m"

    )u$lic void removeMListener!MListener m" =7am)les of invalid JavaBean metod signatures are

    )u$lic void add@Listener!MListener m" listener t)e mismatc

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    9/26

    310-065 C apitre 1

    *M. Romdhani, Fvrier 2009

    Declare Classes

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    10/26

    310-065 C apitre 1

    1+M. Romdhani, Fvrier 2009

    %o&rce ,ile Declaration -&les

    here can be only one +ublic class +er source code file"

    Comments can a++ear at the beinnin or end of any line in the source code file3they are inde+endent of any of the +ositionin rules discussed here"

    If there is a +ublic class in a file, the name of the file must match the name of the+ublic class"

    If the class is +art of a +acae, the +acae statement must be the first line inthe source code file, before any im+ort statements that may be +resent"

    If there are im+ort statements, they must o between the +acae statement (ifthere is one) and the class declaration"

    im+ort and +acae statements a++ly to all classes within a source code file" In

    other words, there's no way to declare multi+le classes in a file and have them indifferent +acaes, or use different im+orts"

    4 file can have more than one non +ublic class"

    %iles with no +ublic classes can have a name that does not match any of theclasses in the file"

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    11/26

    310-065 C apitre 1

    11M. Romdhani, Fvrier 2009

    Class Declarations and .odifiers

    4ccess control in Java is a little tricy because there are four access

    controls (levels of access) but only three access modifiers(+rivate, +rotected, +ublic)"

    ;e fourt access control level !called default or )ac4age access" is#at ou get #en ou don't use an of te tree access modifiers(

    In oter #ords& ever class& metod& and instance varia$le ou declare asan access control& #eter ou e7)licitl t)e one or not( Altoug all four

    access controls !#ic means all tree modifiers" #or4 for most metodand varia$le declarations& a class can be declared with only+ublic ordefault access- te oter t#o access control levels don't ma4e sense for aclass& as ou'll see(

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    12/26

    310-065 C apitre 1

    12M. Romdhani, Fvrier 2009

    Class Access

    Default 4ccess

    A class #it default access as no modifier )receding it in tedeclaration% A class #it default access can be seen only by classeswithin the same +acae(

    0ublic 4ccess

    A class declaration #it te )u$lic 4e#ord gives all classes from all+acaes access to the +ublic class(

    310 065 C i 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    13/26

    310-065 C apitre 1

    13M. Romdhani, Fvrier 2009

    /ther (0onaccess# Class .odifiers

    &ou can modify a class declaration usin the eyword final, abstract, or

    strictf+" Mar4ing a class as strictf+means tat an metod code in te class #ill

    conform to te I=== 3* standard rules for floating )oints(

    %inal Classes

    8en used in a class declaration& te final 4e#ord means te class can't$e su$classed( In oter #ords& no oter class can ever e7tend !inerit from"

    a final class& and an attem)ts to do so #ill give ou a com)iler error( 4bstract Classes

    An a$stract class can never $e instantiated& Its sole )ur)ose is to $ee7tended !su$classed"(

    &ou can't mar a class as both abstractand final" hey have nearly

    o++osite meanins"

    310 065 C it 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    14/26

    310-065 C apitre 1

    14M. Romdhani, Fvrier 2009

    Declare Interfaces

    310 065 C it 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    15/26

    310-065 C apitre 1

    15M. Romdhani, Fvrier 2009

    Declaring an Interface

    hin of an interface as a 566#+ercentabstract class" hese rules are strict 4ll interface methods are im+licitly +ublic

    and abstract"ou do not need to actuallt)e te )u$lic or a$stract modifiers in temetod declaration& $ut te metod is stillal#as )u$lic and a$stract(

    4ll variables defined in an interface mustbe +ublic, static, and final7in oter #ords&interfaces can declare onl constants& notinstance varia$les(

    Interface methods must not be static(

    Because interface metods are a$stract& tecannot $e mar4ed final& strictf)& or native(

    An interface can e7tend one or more otherinterfaces"

    An interface cannot e7tend anting $utanoter interface(

    4n interface cannot im+lement anotherinterface or class"

    Interface t)es can $e used )olmor)icall(

    310 065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    16/26

    310-065 C apitre 1

    1$M. Romdhani, Fvrier 2009

    Declaring Interface Constants

    &ou need to remember one ey rule for interface constants" hey must always be+ublic static final

    Because interface constants are defined in an interface& te don't ave to $edeclared as )u$lic& static& or final( ;e must $e )u$lic& static& and final& but youdon't have to actually declare them that way (

    =7am)le 0 interface Foo int BAR E /-void go!"-

    %or e*am+le, the followin interface definitions that define constants are correctand arre all identical"

    )u$lic int 7 E G- Loo4s non1static and non1final&

    $ut isn't%

    int 7 E G- Loo4s default& non1final&

    non1static& $ut isn't%

    static int 7 E G- Doesn't so# final or )u$lic

    final int 7 E G- Doesn't so# static or )u$lic

    )u$lic static int 7 E G- Doesn't so# final

    )u$lic final int 7 E G- Doesn't so# static

    static final int 7 E G Doesn't so# )u$lic

    )u$lic static final int 7 E G- #at ou get im)licitl

    310 065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    17/26

    310-065 C apitre 1

    1M. Romdhani, Fvrier 2009

    Declare Class .e"ers

    310 065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    18/26

    310-065 C apitre 1

    1)M. Romdhani, Fvrier 2009

    Access .odifiers

    Members can use all four

    )u$lic & )rotected & default& )rivate

    6u$lic Mem$ers

    8en a metod or varia$le mem$er is declared )u$lic& it means all oterclasses& regardless of te )ac4age te $elong to& can access te mem$er!assuming te class itself is visi$le"(

    6rivate Mem$ers

    Mem$ers mar4ed )rivate can't $e accessed $ code in an class oter tante class in #ic te )rivate mem$er #as declared(

    6rotected and Default Mem$ers

    ;e )rotected and default access control levels are almost identical& $ut#it one critical difference( 4 default member may be accessed only ifthe class accessin the member belons to the same +acae,whereas a +rotected member can be accessed (throuh inheritance)

    by a subclass even if the subclass is in a different +acae(

    2ocal /ariables and 4ccess Modifiers

    Can access modifiers $e a))lied to local varia$lesH NO%

    310-065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    19/26

    310-065 C apitre 1

    1*M. Romdhani, Fvrier 2009

    0onaccess .e"er .odifiers

    %inal Methods

    ;e final 4e#ord )revents a metod from $eing overridden in a su$class& and isoften used to enforce te A6I functionalit of a metod( Final Arguments 0 A final argument must 4ee) te same value tat te )arameter

    ad #en it #as )assed into te metod(

    4bstract Methods ou mar4 a metod a$stract #en ou #ant to force su$classes to )rovide te

    im)lementation(

    8ynchroni.ed Methods

    ;e sncroni:ed 4e#ord indicates tat a metod can $e accessed $ onl onetread at a time(

    1ative Methods

    ;e native modifier indicates tat a metod is im)lemented in )latform1de)en dentcode& often in C(

    8trictf+ Methods

    strictf) forces floating )oints to adere to te I=== 3* standard

    Methods with /ariable 4rument 2ists (var#ars)

    Java * allo#s ou to create metods tat can ta4e a varia$le num$er of arguments(

    310-065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    20/26

    310-065 C apitre 1

    2+M. Romdhani, Fvrier 2009

    Constr&ctor Declarations

    very class has a constructor, althouh if you don't create one

    e*+licitly, the com+iler will build one for you"

    hey must have the same name as the class in which they are declared

    Constructor declarations can however have all of the normal accessmodifiers, and they can tae aruments (includin var#ars), -ust lie

    methods"

    Constructors can't be mared static (they are after all associated withob-ect instantiation), they can't be mared final or abstract (becausethey can't be overridden)"

    310-065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    21/26

    310 065 C apitre 1

    21M. Romdhani, Fvrier 2009

    ariale Declarations

    here are two ty+es of variables in Java

    0rimitives A )rimitive can $e one of eigt t)es0 char, boolean, byte, short, int, lon,

    double, or float(

    Reference variables A reference varia$le is used to refer to !or access" an o$9ect( A reference varia$le

    is declared to $e of a s)ecific t)e and tat t)e can never $e canged( Instancearia$les

    Instance variables are the fields that belon to each uni9ue ob-ect" %or thee*am, you need to now that instance variables

    Can use an of te four access levels !#ic means te can $e mar4ed #it anof te tree access modifiers"

    Can $e mar4ed final Can $e mar4ed transient Cannot $e mar4ed a$stract Cannot $e mar4ed sncroni:ed Cannot $e mar4ed strictf) Cannot $e mar4ed native Cannot $e mar4ed static& $ecause ten te'd $ecome class varia$les(

    310-065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    22/26

    310 065 C apitre 1

    22M. Romdhani, Fvrier 2009

    2ocal (4utomatic:8tac:Method) /ariables

    Local varia$les are varia$les declared #itin a metod(

    4rray Declarations

    In Java& arras are o$9ects tat store multi)le varia$les of te same t)e& orvaria$les tat are all su$classes of te same t)e(

    Declarin an 4rray of 0rimitives intK 4e- Suare $rac4ets $efore name !recommended"

    int 4e K- Suare $rac4ets after name !legal $ut less reada$le"

    Declaring an Arra of O$9ect References ;readK treads- Recommended ;read treads K- Legal $ut less reada$le

    %inal /ariables

    Declaring a varia$le #it te final 4e#ord ma4es it im)ossi$le to reinitiali:e tatvaria$le once it as $een initiali:ed #it an e7)licit value( Burn tis in0 tere are no final o$9ects& onl final references

    ransient /ariables

    If ou mar4 an instance varia$le as transient& ou're telling te JM to s4i) !ignore"tis varia$le #en ou attem)t to seriali:e te o$9ect containing it(

    ariale Declarations

    310-065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    23/26

    310 065 C apitre 1

    23M. Romdhani, Fvrier 2009

    ariale Declarations

    /olatile /ariables

    ;e volatile modifier tells te JM tat a tread accessing te varia$lemust al#as reconcile its o#n )rivate co) of te varia$le #it temaster co) in memor(

    8tatic /ariables and Methods

    ;e static modifier is used to create varia$les and metods tat #ill e7istinde)endentl of an instances created for te class( ;ings ou canmar4 as static0

    Metods

    aria$les

    A class nested #itin anoter class& $ut not #itin a metod

    Initiali:ation $loc4s

    310-065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    24/26

    310 065 C apitre 1

    24M. Romdhani, Fvrier 2009

    Declaring n&"s

    he basic com+onents of an enum are its constants

    enum Seasons Automn& 8inter& S)ring& Summer-

    nums can be declared as their own se+arate class, or as a classmember, however they must not be declared within a method ;

    8o what ets created when you mae an enum3

    Coffee drin E new Coffee()3 drin"si.e E Coffee8i.e" /R@2MI1>3

    8ystem"out"+rintln(drinl"si.e"etunces())3 :: +rints ? 8ystem"out"+rintln(drin"si.e" etunces())3 :: +rints 5 FF

    310-065 C apitre 1

  • 7/24/2019 Chap 1 Declarations and Acces Control Update

    26/26

    p

    2$M R dh i F i 2009

    n&"s Constr&ctors

    he ey +oints to remember about enum constructors are

    ou can N==R invo4e an enum constructor directl( ;e enumconstructor is invo4ed automaticall& #it te arguments ou define afterte constant value(

    For e7am)le& BI>!" invo4es te CoffeeSi:e constructor tat ta4es an int&)assing te int literal to te constructor( !Beind te scenes& of course&ou can imagine tat BI> is also )assed to te constructor& $ut #e don'tave to 4no#or carea$out te details("

    ou can define more tan one argument to te constructor& and ou canoverload te enum constructors& 9ust as ou can overload a normal classconstructor(

    8e discuss constructors in muc more detail in Ca)ter /( ;o initiali:e a

    Coffee;)e #it $ot te num$er of ounces and& sa& a lid t)e& ou'd )asst#o arguments to te constructor as BI>!& 5A5"& #ic means ou ave aconstructor in CoffeeSi:e tat ta4es $ot an int and a string(