Constructors 4-2 Example of Parameterized SdaCtoe(nisnttrumc,tionrts d,int y) { month=m; Parameterized Constructor day=d; year=y; System.out.println(\"The Date is \" + m + \"/\" + d + \"/\" + y + \".\"); } public static void main(String args[]) { Sdate S1,S2; S1=new Sdate(11,27,1969); Copyright © 2020 Slide 51 of 92
Constructor Example of Implicit Constructors Sdate() { Implicit Constructors month=11; day=27; year=1969; } public static void main(String args[]) { Sdate S1,S2; S1=new Sdate(); S2=new Sdate()Sli;de 52 of 92 Copyright © 2020
Constructors 4-4 public static void main(String[] args) { Book objBook = new Book(\"CoreJava\", \"Albert\", 45, true) User objUser = new User(); objUser.getBookStatus(objBook); } class User { Book(Strinvgoibdogoekt,BSotoriknSgtaatuutsh(oBr,oionkt poabgjBeoso, bk)o{olean status) { bookName =obbojBoko;ok.isAvailable(); authorNam} e = author; nopages} = pages; available = status; } Demonstrate: Example 1 Copyright © 2020 Slide 53 of 92
Constructors 4-4 • class Message { • /** • * This is a main method. • * @param args passed to the main method • */ • public static void main(String [] args) { • /* Printing the message */ • System.out.println(\"Welcome to Java World! \"); • •} } Slide 54 of 92 Copyright © 2020
Analyzing the Program 3-1 • The symbol /* */ indicates that the statements that follow are comments in that program. The multi line comment begins with /* and ends with */. A single line comment begins with a // and ends at the end of the line. • The keyword class declares the definition of the class. It also helps the compiler to understand that it is a class declaration. • The entire class definition, including all its members, is done within the open ({ ) and closed ( }) curly braces. This marks the beginning and end of the class definition block. Slide 55 of 92 Copyright © 2020
Analyzing the Program • The 3pr-o2gram execution begins from main() method. • The public keyword is an access specifier, which controls the visibility and scope of class members. • The static keyword allows the main() method to be called, without needing to create an instance of the class. • The void keyword tells the compiler that the main() method does not return any value when it is executed. Slide 56 of 92 Copyright © 2020
Analyzing the Program 3-3 • The main() method is the starting point for all Java applications. • Args[] is an array of type String. • The println() method displays the string that is passed to it as an argument with the help of System.out. Slide 57 of 92 Copyright © 2020
Command-Line Argumentclass ArgumentDemo { • In/f*o*rmation can be passed to the main() method dur**ing@Tphtaihrseamipsraoraggsmraapimansesmxeeedthctouodt.iotnhebmyapinasmseintghocdommand-line arpguub*l/micensttsa.tic void main(String[] args) { • TheSsyestaergmu.mouetn.tpsrairnetalcnc(e\"sTsheed bfyolthleowSitnrigngapragruammenettesrsa. re passed during runtime\"); /* Passing the command line arguments */ System.out.println(args[0]); System.out.println(args[1]); System.out.printlCno(mamrgasn[d2-L]i)n;e Argument } } Slide 58 of 92 Copyright © 2020
Type Casting • Type Casting causes the program to treat a variable of one type as though it contains data of another type. Example: // Convert c to an integer float c = 34.89675f; int b = (int) c + 10; Slide 59 of 92 Copyright © 2020
Types of Data Conversion Automatic Type Casting Conversion Casting is used for explicit type conversion. It loses When one type of data is information above the assigned to a variable of magnitude of the value being another type, automatic type converted. conversion takes place provided it meets the following conditions: The two types are compatible. The destination type is larger than the source type. Slide 60 of 92 Copyright © 2020
Example Casting Automatic Type Casting • Declare and initialize the variables Declare the variables • Add the variables and assign the The variables will hold value to the variable of different the values which are data type without explicit type passed during runtime. casting. • No ERROR!!! Add the variable after type casting. long sum; int first, second, sum; first = Integer.parseInt(args[0]); int first = 20, second = Integer.parseInt(args[1]); second = 30; sum = first + second; sum = first + Demonstration: Additional second; Example 1 Demonstration: Additional Example 2 Slide 61 of 92 Copyright © 2020
Type Promotion Rules • All byte and short values are promoted to int type. • If one operand is long, the whole expression is promoted to long. • If one operand is float, the whole expression is promoted to float. • If one operand is double, the whole expression is promoted to double. Slide 62 of 92 Copyright © 2020
Arrays • An array is a data structure that stores data of same data type in consecutive memory locations. • Three ways to declare an array are: • datatype identifier [ ]; • datatype identifier [ ] = new datatype[size]; • datatype identifier [ ] = {value1,value2,….valueN}; • ClassName identifier[] = new ClassName[size]; • Array can have more than one dimension • In Java, Arrays are collection of references Slide 63 of 92 Copyright © 2020
Arrays One Dimensional Array Multi Dimensional Array • It consists of a single Multi Dimensional arrays are column of data of the arrays of arrays. same type. To declare a Multi • An array is declared Dimensional array, additional by specifying its name index has to be specified by and size. using another set of square brackets. Slide 64 of 92 Copyright © 2020
Example • A/r*raAyrDraeyclaIrnaittioinalization */ double[] nums = {2, 0, 1}; • Ai1/Sy*cn0sc}tetP[;ser]simi.nnotnguiunttmhg.bepearairrrnrrsatalyy=ne(ell\"{eeTm8mh,eeenn1vttsa8*l,u/e5,at 2, 1, location 3 • USiysssint:ge\"mt+.hoeunltue.mnpsgr[ti2hn]pt)l;ronp(\"eTrtoytal number of elements in an array is: \"+ numbers.length); System.out.println(\"First element in an array is: \" + numbers[0]); System.out.println(\"Last element in an array is: “ + numbers[numbers.length - Dem1o]n)s;tration: Example 3 and Additional Example 3 Slide 65 of 92 Copyright © 2020
Inheritance 2-1 Inheritance Builds a hierarchy of Keyword classes extends is used to inherit a class Allows to inherit the Child class is a properties and specialized class of the methods of base Parent class class Copyright © 2020 Slide 66 of 92
Inheritance 2-2 Parent class / Base class / Superclass Subclass / Copyright © 2020 Derived class Slide 67 of 92
Advantages of Inheritance Advantages Reusability of Subclass can be code customized easily Data and methods of Designing superclass are applications becomes simpler available to subclass Copyright © 2020 Slide 68 of 92
Inheritance Keyword extends is used. Accessing members of the superclass in the subclass. class Car extends Vehicle { class Vehicle { /** Constructor. */ /** Stores the name of the vehicle. */ Car() { } protected String name = \"Honda Civic\"; /** Display the details of the Ca/r**frSotmortehsethdercivoelodrcdlaestasi.ls*/. */ void show() { protected String color = \"Red\"; System.out.println(\"Lines are/**frSotmordesertihvedsecalatsdsetCaailrs\".);*/ System.out.println(\"Name ofptrhoetevcetheidclient- s\"e+atnsa=m5e;); System.out.println(\"Color of/*th* eCVoenhsitcrulect-o\"r.+*/color); System.out.println(\"NumberVoefhsiecalets() -{ \" + seats); System.out.println(\"=======}=======================\"); } ....... } ....... Demonstration: Example 1 Copyright © 2020 Slide 69 of 92
Derived Class Constructors 2-1 Base class constructor is invoked before the derived class To invoke base class Constructor Inheritance constructor super keyword is used Derived class constructor has same name as that of the class Slide 70 of 92 Copyright © 2020
Derived Class Constructors 2-2 • The syntax to invoke the superclass consructor is: super(parameter_list) or super(); • The parameters required by the constructor of the superclass are specified in the parameter_list • The super() method always refers to the superclass immediately above the calling class. Slide 71 of 92 Copyright © 2020
Invoking Base class Constructor Usage of the keyword super. classS@@//*pp*tcAF**aarulirritacaaDSnhstemmtgo}siorr\"onrtis()neyvatS;ApsemotSnSueedrrayyttyissmhcpphtntteolaaeygeerasspm=msssses..eetes;tsooxdodrtuutrC)ttreotyt..;nonot{ppdysrrsptttiiehrhnnAueettucollttcfcnnhooo((otnrn\"\"r.shsPTetthr{rrieuaunccutntttiahoonmroregr.*if/rs*o/\"m the Author + name); FictionAuthor(String name, String type) { super(name); Calls the super storytype = type; System.out.println(\"Pcrlianstsicnognsfrtroumcttohre Fiction Author class\"); System.out.println(\"Type is \" + storytype); } } Demonstration: Example 3 Copyright © 2020 Slide 72 of 92
Polymorphism 2-1 • Polymorphism means “many forms”. • It is described as ―one interface, many implementations‖. • It helps to write code that does not depend on specific types. • It is the capability of a method to do different things based on the object that is acting upon it. Slide 73 of 92 Copyright © 2020
Polymorphism 2-2Derived Class - Draws and moves Triangle Base Class Triangle draw () { DrawTriangle } move () { MoveTriangleVertices } Multiple inputs (Interface) Derived Class - Draws and moves Rectangle talking to one Shape interface. Rectangle Depending on draw () draw () { input, output is move () DrawRectangle decided } move () { MoveRectangleCorner } Derived Class - Draws and moves Pentagon Pentagon draw () { DrawPentagon } move () { MovePentagonVertices } Slide 74 of 92 Copyright © 2020
Method Overloading Method Overloading More than one Methods have Argument List methods different varies in type having same argument list and / or name in the numbers Slide 75 of 92 class Copyright © 2020
Method Overloading Usage of methods with same name. Argument lists varying in type and / or number. vvovoiodididddidsisipsplpalalyay(y(in(dd)too{nuuubbmlele,ciconoutunntut)m){{1) { SSSySysysytstestemtemem.mo.o.uo.uotutu.pt.pt.rp.rpirnirnitnitnlntlntl(nl(n\"(\"T(\"I\"nhInNsesoidtidwaeerotgthiuhnemetdedegisniesptrpslalnayuyr(me(ddotbohueuebrbrsleelea)f)romemre:de\"tithsh+opondldau:ym:\"\"in++gcc\"!o!o\"uu)n+;ntt)n);u; m1) }}}} public static void main(String [] arg) { int count = 25; DisplayNumber dispObj = new DisplayNumber(); Method accepting dispObj.display(); no argument is dispObj.display(10 , 20); /* No method with a single argumentMoefitnthyvopodekaeincdtceexpitsintsg, int value is automatically promotetdwtoo idnotubalreguments */ is invoked System.out.println(\"Invoking the display(double) method\" + \"with an int variable: \" + count); dispObj.display(count); MMetehtohdodacacecpetpintignga a dispObj.display(25.5); doduobulbelearagrugmumenetnitsis } inivnovkoekded Demonstration: Example 4 Copyright © 2020 Slide 76 of 92
Method Overriding 2-1 Method Overriding Subclass and Superclass super.methodname() is have methods with same used to call the name and type signature superclass version of the method Overridden method of Method in the the subclass will be superclass will be invoked when called by a subclass object hidden Slide 77 of 92 Copyright © 2020
Method Overriding 2-2 Methods with same name and type signatures in the superclass and subclass. Invokes the public static void main(String [] arg) { superclass method Square sqObj = new Square(15); sqObj.getPerimeter(); Invokes the subclass method Rectangle rectObj = new Rectangle(10, 15); rectObj.getPerimeter(); } c.l.acsl.sas.Sqs.uaR.reec.t{a.ngle extends Square { . .. .. .. .. .. .... . * C.al.cul.at.in.g .the. p.erimeter of a square .*/ void* gCeatlPceurlimaettienrg()th{e perimeter of a rectangle .*/ vSoyisdtegme.touPte.rpirmienttelrn((\")Pe{rimeter of a square is \" + (4 * length)); System.out.println(\"Perimeter of a Rectangle } + (2 * (length + width))); }} } Copyright © 2020 Demonstration: Example 5Slide 78 of 92
Dynamic Binding • Super class can refer to sub class. • But super class reference can‘t refer to sub class members. • Sub class cen not refers to super class • Super class will refer to sub class method if it refers to sub class and method is over ridden. Slide 79 of 92 Copyright © 2020
Access Specifier 2-1 • Information hiding is one of the most important features of OOPs. • Reasons for information hiding are: • Changes made to any implementation details will not affect code that uses this class. • Prevents accidental erasure of data by users. • The class is easy to use. Access Specifiers private protected public Default / package specific Slide 80 of 92 Copyright © 2020
Access Specifier 2-2 private public Accessible only to members of the Accessible to class members and non members of the class protected default Accessible to Accessible to members of the members of the class in the same class and members of its package subclass Copyright © 2020 Slide 81 of 92
Method Modifiers Method Modifiers static final synchronized abstract Slide 82 of 92 Copyright © 2020
static Modifier 3-1 • Programmer might need to access a class member independent of any object of the class. • The keyword static is used to create such a member. • Such a member is accessed before any object of the class is created. • For example, main() method is declared static as it can be invoked by the Java runtime system without creating an instance of the class. Slide 83 of 92 Copyright © 2020
static modifier 3-2 Rules Can call other Must access static Cannot use super static methods data or this keyword • Syntax for invoking a static method is: Copyright © 2020 • Classname.methodname(); Slide 84 of 92
static modifier static methods are invoked using class names. public static void main(String [] arg) { //initializing a variable double inch = 66; double feet = InchesToFeet.convert(inches); System.out.println(inch + \" inch is \" + feet + \" feet.\"); } class InchesToFeet { /** Initializes a static variable. */ private static final int inches = 12; /** Constructor. */ protected InchesToFeet() { } public static double convert(double in) { return (in / inches); } D…e…m….onstration: Example 6 Slide 85 of 92 Copyright © 2020
final Modifier final Variable’s content Methods cannot be Reference of cannot be modified overridden by object should not subclass change Slide 86 of 92 Copyright © 2020
abstract Modifier 3-1 • Certain methods in the superclass do not contain any logic and need to be overridden in the subclass. • The keyword abstract is used for such methods. • The subclass provides implementation details of such abstract methods. • The syntax is: • abstract type method_name(parameter_list); • Any class that contains one or more abstract methods must be declared as abstract. • The class keyword should be preceded by the abstract keyword when declaSrlidien8g7 of 9a2 n abstract class.Copyright © 2020
abstract Modifier 3-2 abstract Abstract class Constructors and Abstract method cannot be static methods of superclass has instantiated cannot be abstract to be implemented in subclass • An abstract class can have object references that can point to a subclass object. Slide 88 of 92 Copyright © 2020
abstract Modifier 3-3 Abstract methods do not have any implementation code. }.ap.p.arbrb.sso..otttt.re.er.cacatcct...etetdd...cd..dodl.ouoau..bsu.bbsl.le.l.ceeSl.a.h.arwals.e.iep.s*}S//dean*q**/*..gt(.S@@u**t){hqapph;;urCaas;aoerrurn(aapefsmmeitrenrnn(xuauuntlcmmuet1mndop1dorpa,su.asbssnSlesuhedemad1pnt)euto;mo{1t)hthe{eccononststrurcuctotror * Calculates the area of a square. * @return length passed to the constructor */ double area() { System.out.println(\"Area of a square is : \"); return length * width; } Demonstration}: Example 7 Slide 89 of 92 Copyright © 2020
Interface • Interface is an contract with class that class has to implement functionality • Interface tells only about functionality • Interface doesn‘t tell about implementation • By default all methods are ―public abstract‖ • By default all members are ―public final‖ • To implement an interface, ―implements‖ keyword is being used. • Interface can extends one or more interfaces • Class can implementSslideo90nofe92 or more interfacesCopyright © 2020
Interface interface MyInterface { void call(String name); void wish(String name); } class MyClass implements MyInterface { public void call (String name) { System.out.println (―Hi ― + name); } public wish(String name) { System.out.println (―Have a great day ― + name); } Slide 91 of 92 Copyright © 2020
Summary • Inheritance allows the creation of hierarchical classifications. • Inheritance allows the reusability of code. • All methods and properties of the base class are inherited by objects of the derived class except the constructors. • Polymorphism is the ability of different objects to respond to the same message in different ways. • Overloaded methods are examples of static polymorphism and overridden methods are examples of dynamic polymorphism. Slide 92 of 92 Copyright © 2020
Summary 2-2 • Access specifiers are used to determine how the class members are accessed. • Some of the method modifiers in Java are static, final, abstract. • Interface is a contract for class to provide certain functionality without telling about its implementation. Slide 93 of 92 Copyright © 2020
Exceptions Slide 94 of 92 Copyright © 2020
Review • Inheritance allows the creation of hierarchical classifications. • Inheritance allows the reusability of code. • All methods and properties of the base class are inherited by objects of the derived class except the constructors. • Polymorphism is the ability of different objects to respond to the same message in different ways. • Overloaded methods are examples of static polymorphism and overridden methods are examples of dynamic polymorphism. • Access specifiers are used to determine how the class members are accessed. • Some of the method modifiers in Java are static, final, abstract and synchronized. Slide 95 of 92 Copyright © 2020
Objectives • Define Exception • Explain exception handling • Describe the try, catch and finally blocks • Examine multiple catch blocks • Explore nested try/catch blocks • Explain the use of throw and throws keywords Slide 96 of 92 Copyright © 2020
What is an exception? class ExceptionRaised { /** Constructor. */ p}rote•ctedCExacneptbioenRgaiesend(e)ra{ ted manually in a/** * This method generates an exception. program* @param operand1 is numerator in division Abnormal Condition * @param operand2 is denominator in division OR* @return It will return the remainder of the division. */ • Generated by Javastatic int calculate(final int operand1, final int operand2) { int result = operand1 / operand2; // user defined method Exception returnRreusnulti;me /** * Sole entry point to the class and application. * @param args Array of String arguments. */ Program Terminates Error Handling Benefitspublic static void main(final String[] args) { ExceptionRaised obj = new ExceptionRaised(); Abruptly and control is • Fixes Errortry { given to OS /* The variable result is defined to store the result. */ • Previnetnrtessulatu=toobmj.caatlicculate(9, 0); System.out.println(result); te} rcmatcinh a(Etxicoepntion e) { // Exception object System.err.println(\"Exception occurred :\" + e.toString()); e.printStackTrace(); } } } Slide 97 of 92 Copyright © 2020
Handling Exceptions 2-1 A pseudo code handling a runtime error ……… IF B IS ZERO GO TO ERROR C=A/B PRINT C GO TO EXIT ERROR: BLOCK THAT “CODE CAUSING ERROR DUE TO DIVISION BY ZERO” HANDLES THE EXCEPTION DISPLAY EXIT: END Slide 98 of 92 Copyright © 2020
Handling Exceptions 2-2 Program statements to be monitored are contained within this. Try Clean-up codes get Finally Catch Exceptions caught Executed and handled in rational manner Throw Throws Exceptions thrown Specifies exceptions manually thrown by a method Slide 99 of 92 Copyright © 2020
Hierarchy of Exception classes Object Throwable Error Exception AWTError SQLException RuntimeException ThreadDeath ClassNotFoundException … … ArithmeticException NullPointerException … Slide 100 of 92 Copyright © 2020
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355