Docsity

Java notes (sjbit)(vtuplanet.com), Study notes of Java Programming

Toggle sidebar
bg1
EE2J dna avaJ )357SI60(
ESI fo .tpeD , TIBJS
EE2J dna avaJ
suballyS dna emehcS
357SI60 :edoC tcejbuS 52 :skraM .A.I
sruoH / 40 :keeW 30 :sruoH maxE
25 :sruoH latoT 001 :skraM maxE
TRAP - A
TINU - 1
AVAJ OT NOITCUDORTNI KDJ( tiK tnempoleveD avaJ ;snoitacilppa avaJ dna avaJ : si avaJ ;)
tcejbO ;MVJ ,edoC etyB ,deterpretni - .smargorp avaJ elpmiS ;gnimmargorp detneiro sepyt ataD
,slaretil ,secaps etihw ,syarra ,srotarepo ,rahc ,gnol ,tni ,selbairav naelooB :snekot rehto dna
ccA ;stcejbo gniyortsed dna gnitaerC ;seulav gningissa :snoisserpxE dna srotarepO .sreificeps sse
?ehT ,rotarepO tnemngissA ehT ,srotarepo lanoitaleR ,srotarepo esiwtiB ,srotarepO citemhtirA
sgnirtS ;gnitsac epyT ;noisserpxe lacigoL ;ecnedecerP rotarepO ;rotarepO :stnemetatS lortnoC
eti ,stnemetats noitceleS.stnemetatS pmuJ ,stnemetats noitar
sruoH 6
TINU - 2
:STELPPA ,SNOITPECXE ,ECNATIREHNI ,SESSALC gniralceD ;avaJ ni sessalC :sessalC
.sessalc rennI ;ssalc fo secnatsni gnitaerC ;srotcurtsnoC ;sessalc repuS ;eman ssalC ;ssalc a
tlum ,elpmiS :ecnatirehnI noitpecxE .gnidaolrevo ,gnidirrevO ;ecnatirehni levelitlum dna ,elpi
gnildnah: ;scisab telppA ;stelppA fo sepyt owT :ssalC telppA ehT .avaJ ni gnildnah noitpecxE
;gnitniaper gnitseuqeR ;sdohtem yalpsid telppA elpmiS ;noteleks telppA nA ;erutcetihcrA telppA
;stelppA ot sretemarap gnissaP ;gat TELPPA LMTH ehT ;wodniW sutatS eht gnisU
pilCoiduA ehT ;)(tnemucoDwohs dna txetnoCtelpA ;)(esabedoCteg dna )(esabtnemucoDteg
.elosnoC eht ot tuptuO ;ecafretnI butStelppA ehT ;ecafretnI
sruoH 6
TINU - 3
DAERHT ITLUM:GNILDNAH TNEVE ,GNIMMARGORP DE dedaerhT itluM
;sdaerht gnidnetxE ;elbadaerht sessalc eht ekam ot woH ?sdaerht era tahW :gnimmargorP
reffub dednuoB ;daerht eht fo etats gnignahC ;noitazinorhcnyS ;elbannur gnitnemelpmI
daer ,smelborp - recudorp ,melborp etirw - :gnildnaH tnevE .smelborp remusnoc tneve owT
tnevE ;stneve fo secruoS ;sessalc tnevE ;ledom tneve noitageled ehT ;smsinahcem gnildnah
.sessalc rennI ;sessalc retpadA ;ledom tneve noitageled eht gnisU ;secafretni renetsil
sruoH 7
TINU - 4
:SGNIWS wS ;sreniatnoC dna stnenopmoC ;serutaef gniwS yek owT ;gniwS fo snigiro ehT :sgni
dna lebalJ ;telppA gniwS a etaerC ;noitacilppA gniwS elpmis A ;segakcaP gniwS ehT
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e

Partial preview of the text

Download Java notes (sjbit)(vtuplanet.com) and more Study notes Java Programming in PDF only on Docsity!

De pt.ofIS E, SJBIT

JavaandJ 2 E E

SchemeandSyllabu s

Su bjectCode: 06 IS 753 I.A.Marks: 25

Ho ur s/ We ek: 04 ExamHours: 03

To talHours: 52 ExamMarks: 100

PA R T- A

UN I T- 1

IN TRODUCTIONTOJAV A : JavaandJavaapplications;JavaDevelopmentKit(JDK);Javais

in terpreted,ByteCode,JVM;Objec t- or ientedprogramming;SimpleJavaprograms. Datatypes

andothertokens: Booleanvariables, int, long,char,operators,arrays,white spaces,literals ,

as signingvalues;Creatinganddestroyingobjects;Ac cessspecifiers.OperatorsandExpressions:

ArithmeticOperators,Bitwiseoperators,Relationaloperators,TheAssignmentOperator,The?

Op erator;OperatorPrecedence;Logicalexpression;Typecasting;String s ControlStatements:

Se lectionstatements,it erationstatements,JumpStatements.

6 Hour s

UN I T- 2

CL ASSES,INHERITANCE,EXCEPTIONS,APPLETS : Classes:ClassesinJava;Declaring

a class; Class name;Superclasses; Constructors;Creatinginstances of class; Innerclasses.

In heritance:Simple, mul tiple,andmultilevelinheritance; Overriding, overloading. Exception

ha ndlin g : ExceptionhandlinginJava.TheAppletClass:TwotypesofApplets;Appletbasics;

AppletArchitecture;AnAppletskeleton;SimpleAppletdisplaymethods;Requestingrepainting ;

Using the Status Window; The HTML APPLET tag; Passing parameters to Applets ;

getDocumentbase() and getCodebase(); ApletContext and showDocument(); The AudioCli p

Interface;TheAppletStubInterface;OutputtotheConsole.

6 Hour s

UN I T- 3

MU LTI THREA DED PROGRAMMING, EVENT HANDLING: Multi Threaded

Programming: What are threads? How tomake the classes threadable; Extending threads ;

Implementing runnable; Synchronization; Changing state of the thread; Bounded buffe r

pr oblems, rea d- wr ite problem, producer- co nsumer problems. Event Handling:Two event

handlingmechanisms;Thedelegationeventmodel;Event classes; Sources ofevents;Even t

listenerinterfaces;Usingthedelegationeventmodel;Adapterclasses;Innerclasses.

7 Hour s

UN I T- 4

SW INGS : Sw ings:TheoriginsofSwing;TwokeySwingfeatures;ComponentsandContainers;

The Swing Packages; A simple Swing Application; Create a Swing Applet; Jlabel an d

De pt.ofIS E, SJBIT

ImageIcon; JTextField;The Swing Buttons; JTabbedpane; JScrollPane; JList; JComboBox ;

JTable.

7 Hours

PA R T- B

UN I T- 5

JA VA 2 ENTERPRISEEDITIONOVERVIEW,DATABASEACCESS : OverviewofJ 2 EE

andJ 2 SE.TheConceptofJDBC;JDBCDriverTypes;JDBCPackages;ABriefOverviewofth e

JD BCprocess;DatabaseConnection;AssociatingtheJDBC/ODBCBr idgewiththeDatabase;

StatementObjects;ResultSet;TransactionProcessing;Metadata,Datatypes;Exceptions.

6 Hour s

UN I T- 6

SE RVLETS : Background;TheLifeCycleofaServlet;UsingTomcatforServletDevelopment;

A simpleServlet;TheServletAPI ;TheJavax.servletPackage;ReadingServletParameter;The

Javax.servlet.httppackage;HandlingHTTPRequestsandResponses;UsingCookies;Sessio n

Tracking.

7 Hour s

UN I T- 7

JS P,RMI : Ja vaServerPages(JSP):JSP,JSPTags,Tomcat,RequestString,UserSessions,

Co okies,SessionObjects.JavaRemoteMethodInvocation :RemoteMethodInvocationconcept;

Serverside,Clientside.

6 Hour s

UN I T- 8

EN TERPRISEJAVABEANS : EnterprisejavaBeans;DeploymentDescriptors;SessionJava

Be an,EntityJavaBe an; Message- DrivenBean;TheJARFile.

7 Hour s

TEXTBOOKS :

  1. Ja va- Th eCompleteReference – He rbertSchildt, 7

th Edition,TataMcGrawHill,

  1. J 2 EE- Th eCompleteReference – JimKeogh,TataMcGrawHill, 2007.

REFERENCEBOOKS :

  1. In troduction to JAVA Progr amming – Y. Daniel Liang, 6

th Edition, Pearson Education, 2007.

  1. Th eJ 2 EETutorial – St ephanieBodoffetal, 2

nd Edition,PearsonEducation, 2004.

De pt.ofIS E, SJBIT

Extendingthreads;Implementingrunnable;Synchronization;Changingstateo f

th ethread;Boundedbuff er problems

30

Re a d- wr iteproblem,producer- co nsumerproblems^33

Tw oeventhandlingmechanism s 35

Th edelegationeventmodel;Eventclasses;Sourcesofevent s^36

Ev entlistenerinterfaces;Usingthedelegationeventmode l 37

Ad apterclasses;Inne rcl asses^39

4 SW INGS 42 - 49

Sw ings:TheoriginsofSwing;TwokeySwingfeature s^42

Co mponentsandContainer s 42

Th eSwingPackages;AsimpleSwingApp lic ation^45

Cr eateaSwingApple t 46

Jl abelandImageIco n^47

JT extField;TheSwingButtons;JTabbedpan e 48

JS crollPane;JList;JComboBox;JTabl e^49

5 JA VA 2 ENTERPRISEEDIT IONOVERVIEW,DATABA SEACCESS: 50 - 53

Ov erviewofJ 2 EEandJ 2 SE.

50

Th eCo nceptofJDBC;JDBCDriverTypes;JDBCPackages 50

A BriefOverviewoftheJDBCprocess;DatabaseConnection ; 50

As sociatingtheJDBC/ODBCBridgewiththeDatabase ; 51

St atementObjects,ResultSet ;^52

Tr ansactionProcessingMetadata,.Datatyp es; Exceptions. 53

6 SE RVLETS^54 -^60

Ba ckgroun d 54

TheLifeCycleofaServlet;UsingTomcatforServletDevelopment;Asimpl e Se rvle t

54

Th eServletAPI;TheJavax.servletPackag e^55

De pt.ofIS E, SJBIT

  • Re adingServletParameter;TheJavax.servlet.httppackag e
  • Ha ndlingHTTPRequestsandResponse s
  • Us ingCookie s
  • Se ssionTracking
  • 7 JS P,RMI^61 -
    • Ja vaServerPages(JSP):JSP,JSPTag s
    • To mcat,RequestString,UserSession s
    • Co okies,SessionObject s
    • Ja vaRemoteMethodInvocation :Re mote MethodInvocationconcept
    • Se rversid e
    • Cl ientside
    • KS IM C
    • Di csinglewindowsagencySISI,NSIC,SIDBI,KSF C
  • 8 EN TERPRISEJAVABEANS 66 -
    • En terprisejavaBeans ;
      • De ploymentDescriptor s
    • Se ssionJavaBea n
    • En tityJavaB ean ;
    • Me ssag e- Dr ivenBean,TheJARFile.

1. 1 .IntroductiontoJava

x Ja vaisanobject- orientedprogramminglanguagedevelopedbySunMicrosystems,a

co mpanybestknownfo rit shigh- endUnixworkstations.

x JavaismodeledafterC++

x Javalanguagewasdesignedtobesmall,simple,andportableacrossplatformsand

operatingsystems,bothatthesourceandatthebinarylevel(moreaboutthislater).

x Ja vaalsoprovidesforportableprogrammingwithapplets.AppletsappearinaWeb

pagemuchinthesamewayasimagesdo,butunlikeimages,appletsaredynamican d

interactive.

x Appletscanbeusedtocreateanimations,figures,orareasthatcanrespondtoinput

fr omthereader,g ames,orotherinteractiveeffectsonthesameWebpagesamongthe

textandgraphics.

1. 1. 2 Ja vaIsPlatform- Independent

Pl atfor m- in dependence is aprogram'scapability of movingeasilyfrom one computer

systemtoanother.

x Pl atformindependenceisoneofthemostsignificantadvantagesthatJavahasoverother

programming languages, particularly for systems that need to work on many differen t

platforms.

x Ja vaisplatform- independentatboththesourceandthebinarylevel.

1. 1. 2 Ja vaDevelopmentKit(JDK)- By tecode

x By tecodes areasetofinstructionsthatlookalotlikemachinecode,butarenotspecificto

anyoneprocesso r

x Pl atform- independencedoesn'tstopatthesourcelevel,however.Javabinaryfilesarealso

pl atfor m- in dependentandcanrunonmultipleplatformswithout theneedtorecompilethe

source.Javabinaryfilesareactuallyinaformcalledbytecodes.

1. 1. 3 Ob ject- OrientedProgramming

x Ma nyofJava'sobject- orientedconceptsareinheritedfromC++,thelanguageonwhichit

is based,butitbo rro wsmanyconceptsfromotherobject- orientedlanguagesaswell.

x Javaincludesasetofclasslibrariesthatprovidebasicdatatypes,systeminputandoutput

capabilities,andotherutilityfunctions.

x T hese basicclasses arepartoftheJavadevelopmentkit,whichalsohasclassesto

supportnetworking,commonInternetprotocols,anduserinterfacetoolkitfunctions.

x BecausetheseclasslibrariesarewritteninJava,theyareportableacrossplatformsas

allJavaapplicationsare.

1. 1. 4 Cr eating a simple Java Program

HelloWorldexample :

classHelloWorld {

publicstaticvoidmain(Stringargs[]) {

System.out.println("HelloWorld!") ;

}

}

Thisprogramhastwomainparts :

x Al l the program is enclosed in a class definition— here, a class called

HelloWorld.

x T heb odyoftheprogram(here,justtheoneline)iscontainedinamethod(function)

ca lledmain().InJavaapplications,asinaCorC++program,main()i sthefirstmethod

(function)thatisrunwhentheprogramisexecuted.

1. 1. 5 Co mpilingtheaboveprogram:

x InSun'sJDK,theJavacompileriscalledjavac.

javacHelloWorld.jav a

x Whentheprogramcompileswithouterrors,afilecalledHelloWorld.classiscreated,

inthesamedirectoryasthesourcefile.ThisistheJavabytecodefile.

x T henrunthatbytecodefileusingtheJavainterpreter.IntheJDK,theJavainterpreter

iscalledsimplyjava.

javaHelloWorl d

Iftheprogramwastypedandcompiledcorrectly,theoutputwillbe :

"HelloWorld! "

1. 2 VariablesandDataTypes

x Va riablesarelocationsinmemoryinwhichvaluescanbestored.Theyhaveaname,

Th echar typeisusedforindividualcharacters.BecauseJavausestheUnicodecharacter

set,thechartypehas 16 bitsofprecision,unsigned.

1. 2. 4 Boolean

Th ebooleantypecanhaveoneoftwovalues,trueorfalse.Notethatunlikeinother C-

li kelanguages,boo leanisnotanumber,norcanitbetreatedasone.AlltestsofBoolean

variablesshouldtestfortrueorfalse.

1. 2. 5 Literals

LiteralsareusedtoindicatesimplevaluesinyourJavaprograms.

NumberLiteral s

x T hereareseveralintegerliterals. 4 ,forexample,isadecimalintegerliteraloftype in t

x Adecimalintegerliterallargerthananintisautomaticallyoftypelong.

x Fl oating- po intliteralsusuallyhavetwoparts:theintegerpartandthedecimalpart— forexample, 5. 677777.

BooleanLiteral s

B oole anliteralsconsistofthekeywordstrueandfalse.Thesekeywordscanbeused

anywhereneededatestorastheonlypossiblevaluesforbooleanvariables.

1. 2. 6 CharacterLiterals

C haracterliteralsareexpressedbyasinglecharactersurroundedbysingl equotes:'a','#',

' 3 ',andsoon.Charactersarestoredas 16 - bitUnicodecharacters.

1. 3 ExpressionsandOperators

x Expressions are the simplest form of statement in Java that actually a ccomplishessomething. E xpressions arestatementsthatreturnavalue.

x Op er ators arespecialsymbolsthatarecommonlyusedinexpressions.

Arithmetic and tests for equality and magnitude are common examples o f

expressions.Becausetheyreturnavaluethevaluecanbeassignedtoavariableo r

t estthatvalueinotherJavastate ments.

OperatorsinJavaincludearithmetic,variousformsofassignment,incrementan d

decrement,andlogicaloperations.

1. 3. 1 Arithmetic

Javahasfiveoperatorsforbasicarithmeti c

Arithmeticoperators.

Operato r

Meanin g

Exa m

pl e

  • A ddition 3 + 4

— S ubtra ction 5 —

  • Multiplication 57 * 5

/ Di vision 14 / 7

% Modulus 20 % 7

Exampleprogram :

classArithmeticTest {

publicstaticvoidmain(Stringargs[]) {

s hortx= 6 ;

inty= 4 ;

floata= 12. 5 f ;

floatb= 7 f ;

System.out.println("xis"+ x

", y is "

y);

System.out.println("x+y=" +

Sy stem.out.println(" x- y="+

System.out.println("x/y=" +

System.out.println("x%y=" +

( x ( x ( x ( x +y)) ;

  • y));

/y)) ;

y));

b;

System.out.println("ais"+a+",bis "

Sy stem.out.println("a/ b="+(a/b)); } }

Assignmentoperators.

ExpressionMeanin g

x += y x=x+y

x — = yx=x— y

x = y x=xy

x =x/ yx/=y

IncrementingandDecrementin g

x++ increments thevalueofxby 1 just as ifyouhadusedthe expressionx= x+ 1.

Si milarly x-- decrementsthevalueofxby 1.

< < Leftshift

Rightshift

Zerofillrightshift

~ Bitwisecomplement

< < = Leftshiftassignment(x=x<<y)

= Rightshiftassignment(x=x>>y)

= Ze rofillrightsh iftassignment(x=x>>>y)x&=y

ANDassignment(x=x&y )

x| = y ORassignment(x+x|y)

x^ = y XORassignment(x=x^y)

OperatorPrecedenc e

Operatorprecedence determines theorderinwhichexpressions are evaluated. This,i n

s omecases,candetermi ne the overallvalueofthe expression.Forexample,takethe

followingexpression :

y= 6 + 4 / 2

Dependingonwhetherthe 6 + 4 expressionorthe 4 / 2 expressionisevaluatedfirst,th e

va lueofycanendupbeing 5 or 8 .Ingeneral,incrementanddecrem entareevaluated

before arithmetic, arithmetic expressions are evaluated before comparisons, an d

comparisons are evaluated before logical expressions. Assignment expressions ar e

evaluatedlast.

1. 4 Arrays

Ar raysinJavaareactualobjects thatcanbepass edaroundandtreatedjustlikeother

objects.

A rray s areawaytostorealistofitems.Eachslotofthearrayholds anindividual

element,andyoucanplaceelementsintoorchangethecontentsorthoseslots asyo u

needto.

Th reestepstocreateanarr ay:

  1. Declareavariabletoholdthearray.
  1. Createanewarrayobjectandassignittothearrayvariable.

  2. Storethingsinthatarray.

E.g.

String[]names ;

names=newString[ 10 ] ;

na mes[ 1 ] = “n 1 ”;

na mes[ 2 ] = ‘n 2 ’;

1. 4. 1 MultidimensionalArrays

J avadoesnotsupportmultidimensionalarrays.However,youcandeclareandcreatean

array of arrays (and those arrays can contain arrays, and so on, for however man y

di mensionsyouneed),andaccessthemasyouwould C- stylemultidimensionalarrays:

in tc oords[][]=newint[ 12 ][ 12 ];

coords[ 0 ][ 0 ]= 1 ;coords[ 0 ][ 1 ]= 2 ;

1. 5 ControlStatement

1. 5. 1 ifConditionals

x Theifconditional,whichenablesyoutoexecutedifferentbitsofcodebasedona

s impletestinJava,isnearlyidenticaltoifstatementsi nC.

x ifconditionalscontainthekeywordif,followedbyabooleantest,followedbya

statement(oftenablockstatement)toexecuteifthetestistrue :

x if(x<y)

System.out.println("xissmallerthany") ;

An optionalelsekeywordprovidesthestatement toexecuteifthetestisfalse:

if(x<y )

Sy stem.out.println("x is smaller than y") ; else

System.out.println("yisbigger") ;

1. 5. 2 TheConditionalOperator

Analternativetousingtheifandelsekeywordsinaconditionalstatementistouseth e

co nditio naloperator,sometimescalledtheternaryoperator.

1. 5. 4 forLoops

Th eforloop,asinC,repeatsastatementorblockofstatement ssomenumberoftimes

untilaconditionismatched.forloopsarefrequentlyusedforsimpleiterationinwhic h

yourepeatablockofstatementsacertainnumberoftimesandthenstop,butyoucanus e

forloopsforjustaboutanykindofloop.

Th eforlo opinJavalooksroughlylikethis:

fo r(initialization;test;increment) {statements;

Thestartoftheforloophasthreeparts :

x In itializationi sanexpressionthatinitializesthestartoftheloop.Ifyouhavealoop

in dex,thisexpressionmightdec lar eandinitializeit,forexample,inti= 0 .Variablesthat

yo udeclareinthispartoftheforlooparelocaltotheloopitself ;theyceaseexistingafter

th eloopisfinishedexecuting .T estisthetestthatoccursaftereachpassoftheloop.

Th e te st must be a booleanexpressionorfunctionthat returns a boolean value,for

ex ample,i< 10 .Ifthetes tistrue,theloopexecutes.Oncethetestisfalse,theloop

stopsexecutin g

  • In crement is anyexpression orfunctioncall. Commonly, theincrement is usedto

ch angethevalueoftheloopindextobringthestateoftheloopclosertoreturnin gfalse

andcompleting.

Thestatementpartoftheforloopisthestatementsthatareexecutedeachtimetheloo p

it erates.Justaswithif,youcanincludeeith erasinglestatementhereorablock;the

previousexampleusedablockbecausethatismorecommon.Here'sanexampleofafo r

loopthatinitializesallthevaluesofaStringarraytonullstrings :

St ringstrArray[]=newString[ 10 ] ;int

i;//loopinde x

for (i = 0 ; i < strArray.length; i++ )

strArray[i]="" ;

1. 5. 5 whileanddoLoops

Finally,therearewhileanddoloops.whileanddoloops,likeforloops,enableablocko f

J avacodetobeexecutedrepeatedlyuntilaspecificconditionismet.Whethery ouusea

fo rloop,awhile,oradoismostlyamatterofyourprogrammingstyle .whileanddo

lo op,areexactlythesameasinCandC++excepttheirtestconditionmus tbeaboolean.

1. 5. 6 whileLoops

Th ewhileloopisusedtorepeatastatementorbloc kofstatementsaslongasaparticular

conditionistrue.whileloopslooklikethis :

while (condition) {

bodyOfLoop; }

Th e c ondition isabooleanexpression.Ifitreturnstrue,thewhileloopexecutesthe

s tatementsinbodyOfLoopandthentests thecond itionagain,repeatinguntilthe

conditionisfalse :

intcount= 0 ;

while(count<array 1 .length&&array 1 [count]!= 0 ) {

array 2 [count]=(float)array 1 [count++] ;

1. 5. 7 do...whileLoops

Th edoloopisjustlikeawhileloop,exceptthatdoexecutes agivenstatementorblock

untiltheconditionisfalse.Themaindifferenceisthatwhileloopstesttheconditio n

before looping,makingit possiblethatthebodyofthe loopwillneverexecuteifth e

co nditionisfalsethefirsttimeit'stested.doloop srunthebodyoftheloopatleastonce

beforetestingthecondition.doloopslooklikethis :

do {

bodyOfLoop ;

} whil e (condition);

Here,thebodyOfLooppartisthestatementsthatareexecutedwitheac h

intx= 1 ;

do {

Sy stem.out.println("Looping,roun d" +x);x++;

}while(x<= 10 ) ;

Here'stheoutputofthesestatements :

Looping,round 1 Looping,round 2 Looping,round 3 Looping,round 4 Looping,round 5

Looping,round 6

Lo oping,roundLooping,roundLooping,roun dLooping,round

2. 1. De finingClasses,ClassName

x To defineaclass,usetheclasskeywordandthenameoftheclass:

classMyClassName {

x Ifthisclassisasubclassofanotherclass,useextendstoindicatethesuperclassofthis

class :

classmyClassNameextendsmySuperClassName {

x If thisclassimplementsaspecificinterface,useimplementstorefertothatinterface:class

MyRunnableClassNameimplementsRunnable {

SuperClasse s

x Eachclasshasasuperclass(theclassaboveitinthehierarchy),andeachclasscanhaveone

or moresubclasses(classesbelowthatclassinthehierarchy).Classe sfurtherdowninthe

hierarchyaresaidtoinheritfromclassesfurtherupinthehierarchy.

x Su bclassesinheritallthemethodsandvariablesfromtheirsuperclasses— thatis, inany

pa rticularclass,ifthesuperclassdefinesbehaviorthatyourclassneed s,youdon'thaveto

redefine itorcopythat codefromsome otherclass.Yourclass automaticallygets tha t

behaviorfromitssuperclass,thatsuperclassgetsbehaviorfromitssuperclass,andsoonal l

thewayupthehierarchy.

x At thetopoftheJavaclass hierarchyistheclassObject; allclassesinheritfromthisone

superclass.Objectisthemostgeneralclassinthehierarchy;itdefinesbehaviorinheritedb y

al ltheclassesintheJavaclasshierarchy.Eachclassfartherdowninthehierarchyaddsm ore

informationandbecomesmoretailoredtoaspecificpurpose.

E .g.

publicclassHelloAgainAppletextendsjava.applet.Applet{ }

2. 2 Constructors,Creatinginstancesofaclass

Th efollowingexampledemonstratesthecreationofclasses,creatingobject sandtheusageof

constructor s

classMotorcycle{ }

createsomeinstancevariablesforthisclas s

Stringmake;Stringcolor;booleanengineState ;

Addsomebehavior(methods)totheclass.

voidstartEngine() {

if(engineState==true )

Sy stem.out.println("Th eengineisalreadyon.");else{

engineState=true ;

System.out.println("Theengineisnowon."); }

Theprogramlookslikethisnow :

classMotorcycle {

Stringmake ;

Stringcolor ;

booleanengineState ;

voidstartEngine() {

if (engineS tate == true )

Sy st em.out.println("The

else {

engineState = true ;

System.out.println("The }

engine is alread y

on.") ;

engine is no w

on.") ;

TheshowAttsmethodprintsthecurrentvaluesoftheinstancevariablesinaninstanceofyou r

Mo torcycleclass.Here'swhatitlook slike:

voidshowAtts() {

System.out.println("Thismotorcycleisa"+color+""+make) ;

if(engineState==true )

System.out.println("Theengineison.");elseSystem.out.println("Theengineisoff.") ;