0% found this document useful (0 votes)
19 views22 pages

UNIT 3 JAVA Programming

The document outlines the syllabus and key concepts of a Java programming module, focusing on classes, methods, and object-oriented programming principles. It covers class fundamentals, object declaration, method overloading, constructors, and garbage collection, providing examples and explanations for each topic. The content is structured into chapters that detail the creation and manipulation of classes and objects in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
19 views22 pages

UNIT 3 JAVA Programming

The document outlines the syllabus and key concepts of a Java programming module, focusing on classes, methods, and object-oriented programming principles. It covers class fundamentals, object declaration, method overloading, constructors, and garbage collection, providing examples and explanations for each topic. The content is structured into chapters that detail the creation and manipulation of classes and objects in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Basis of Java Programining Modul BPLCK205C MODULE-3 Chapter 1: Introducing Classes Chapter 2: A Closer Look at Methods and Classes Syllabus: Chapter 1: 1. Class Fundamentals (i) The General Form of a Class (ii) 4 Simple Class 2. Declaring Objects (i) ACloser look at new 3. Assigning Object Reference Variables 4. Introducing Methods (i) Adding a Method to the Box Class (i) Returnings Value (uit) Adding a Method That Takes Parameters 5. Constructors (i) Parameterized Constructors 6. The this Keyword (i) Instance Variable Hiding 7. Garbage Collection The finalize() Method. 9. a Stack Class 2 Chapter 2: 1. Overloading Methods (i) Overloading Constructors Using Objects as Parameters A Closer Look at Argument Passing Returning Objects Recursion Introducing Access Contral Understanding static Introducing final Arrays Revisited SPN Pee eS Prof, Ashwini G Dept of CSE, MITT Pagel Basis of java Programmin Module-3 BPLCK205C Chapter 1: Introducing Classes The class is at the core of fava, = Ik is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object. 1. Class Fundamentals = Class defines a new data type, Once defined, chis new type can be used to create objects of that type. + Aclassis a template for an object, and an object is an instance of a class. = Because an object is an instance of a class, you will often see the two words object and instance used interchangeably G) The General Form ofa Class «When you define a class, you declare its exact form and nature, You do this by specifying the data that it contains and the cade that operates on that data. + Aclass is declared by use of the class keyword. // General form of a class definition class classname { type instance-variablel; type instance-variable2; ae type instance-varisblen; type methodnamel(parsmeter-list) { Wf body oF method t type methodnameN(parameter-list) 4 #4 body of method + 3 + The data, or variables, defined within a class are called instance variables, + The code is contained within methods. + Collectively, rhe methods and variables defined within a class are called members of the class, + Variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables, + Thus, the data for one object is separate and unique from the data for another. Prof Ashwini @ Dept of CS&E, MITT Page 2 Basis of Java Programming Module-3 BPLCK205¢ (ii) A Simple Class + Here is a class called Box that defines three instance variables: width, height, and depth. class Box { double width; double height; double depth; , + Asstated, aclass defines anew type of data, + Inthis case, the new data type is called Box. + You will use this name to declare objects of type Box. + Itis important to remember that a class declaration only creates a template: it does not create an actual object + To actually create a Box object, use the following statement Box mybox = new Box(); | // create a Box object called mybox + Afver this statement executes, mybox will be an instance of Box + Thus, it will have “physical” reality. Thus, every Box object will contain ies own copies of the instance variables width, height, and depth, + Toaccess these variables, you will use the dot (.) operator. + The dot operator links the mame of the object with the name of an instance variable. + For example: To assign the width variable of mybox the value 100, you would use the following statemen ‘[Link] 77 & program that uses the Box class. Box@[Link] class Box { OUTPUT double width; Volume is. 3000.0 double height; double depth; [1a ead decree a cifect-oF type mae: class BoxDeno t public static void main(String args{1) { Box myhox double vol; new Box()5 Dept. of CS&E, MITT Page 3 Basis of Java Programming Module-3 BPLCK205C // assign values to mybox's instance varisbles [Link] = 18; [Link] = 28; [Link] = 15; 17 compute volume of box vol = [Link] * [Link] * [Link]; [Link]( "Volume is " + vol); Declaring Objects + When you create a class, you are creating a new data type, = However, obtaining objects of a class is a two-step process. 1, First, you must declare a variable of the class type, This variable does not define an object Instead, itis simply a variable that can refer to an object. Box mybox(}; // declare reference to object 2, Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the mew operator. myboxenew dox(}; // allocate 3 Box object + Aline similar to the following is used to declare an object of type Box: Box mybox=new Box(}; = The effect of First and Second step of code is depicted as shown below mybox = new Box: ee [wan | Box object Prof Ashwini G Dept. of CS&E, MITT Page + Basis of Java Frogramming Module-3 BPLCK205¢ (i) A Closer Lookatnew * mew operator dynamically allocates memory for an object. + General Form: class-varsnew classname(); * Here, class-var is a variable of the class type being created. The classname is the name of the class thatis being instantiated. + The class name followed by parentheses specifies the constructor for the class. + Aconstructor defines what occurs when an object of a class is created, © A dlass creates a logical framework that defines the relationship between its members. © When you declare an object of class, you are creating an instance of that class. + Addass isa logical construct. An object has physical reality. 3. Assigning Object Reference Variables «Object reference variables act differently when an assignment takes place. Box bl = new Box(); Box b2 = bi; «The situation is depicted her + Afver this fragment executes, bil and b2 will both refer to the same object. «The assignment of bi to b2 did not allocate any memory or copy any part of the original object. + Irsimply makes b2 refer to the same object as does b1. «Thus, any changes made-to the object through b2 will affect the object to which bi is referring, since they are the same object «Although bi and b2 both refer to the same object, they are not linked in any other way. Box bl = new Box(); Box b2 = bl; feces bi = null; Here, bi has been set te null, but b2 still points to the original object. Prof, Ashwini G Dept of (SRE, MITT Pages Basis of Java Programming Module-3 4, Introducing Methods + This the general form of a method: type name(parameter-list) { Jf body of method } EPLCK205C + Here, type specifies the type of data returned by the method. This can be any valid type, including class types that you create. + Ifthe method does not return a value, its return type must he void. + The name of the method is specified by name. + The parameter-list is a sequence of type and identifier pairs separated by commas. + Parameters are essentially variables that receive the value of the arguments passed to the method when itis called. + Ifthe method has no parameters, then the parameter list will be empty. + Mechod: that have a return type other than void return 3 value to the calling routine using the following form of the return statement: return value; + Here, value is the value returned, (i) Adding a Method to the Box Class class Box { double width; ouTPUT double height; Volume is 3000.0 double depth; Volume is 162.8 / display volume of a box void volume() { [Link]("Volume is ") [Link](width * height * depth); } } class BoxDeno3 £ public static void main(String argsf]) { Box mybox1 = new Sox(); Jf assign values to myboxi's instance variables [Link] = 1a; [Link] = 2 [Link] = 15; df display volume of box myboxi .volume{); } } Prof, Ashwini G Dept. of CS&E, MITT Pages Basis of Java Programming Module-3 EPLCK205C [Link](}; = The first line here invokes the volume ) method on mybort. + Thatis,it calls volume() relative to the mybox! object. using the object's name followed by the dot operaror. + Thus, the call to [Link]( ) displays the volume of the box defined by myboxi. (i) Returning a Value + While the implementation of volume( ) does move the computation of a box's volume inside the Box class where it belongs, it is not the best way to do it class Sox { double width; our double height; Volume is 3002.8 double depth; ‘/ compute and return volume double volume(} i width*height ‘depth; } ) class Boxdesod : public static void'main(String args ]) _ mybox1 = new 8ox(); double vol; // assign values to myboxt's instance variables ‘myborl width = 18; [Link] = 20; [Link] = 15; /f get voluma of box vol=mybox1 volume(); [Link](® Volume is: + vol); 1 } + As you can see, when volumef ) is called, ix is put on the right side of an assignment statement. + On the leftis a variable, in this case vol, that will receive the value returned by volume(}. + Thus, after vol = [Link]); executes, the value of [Link] ) is 3,000 and this value then is stored in val. SH Prof, Ashwini G Dept of CS&E, MITT Page 7 Basis of Java Frogramming Module-3 EPLCK205C i) Addinga Method That Takes Parameters = While some methods don't need parameters, most do. Parameters allow a methed to be generalized. + That is, a parameterized methed can operate on a variety of data and/or be used ina number of slightly different situations. J This program uses 2 parameterized method. class Box t double width; ouTpuT double height; volume is 3908.6 double depth; / compute and return volume double volune() 1 return width*height*depth; } void setOin(double w,double h, double 4) 1 width=w; height=h; dapth=d; ? } class BoxtesoS. { public "static void main(String args[]) 1 Box myboxl = new 8ox¢); double vol; 4/ initialize box mybox1. setOim(18, 28,15}; #7 get volume of box val=myboxt .wolume(); [Link](” Volume is:" + vol); } ? + Asyou-can see, the setDim() method is used to set the dimensions of each box For example, when [Link](20, 20, 15); is executed, 10 is copied into parameter w, 20 is copied into h, and 15 is copied into d. + Inside setDim({) the values of w, h, and d are then assigned to width, height, and depth, respectively. Dept. of CS&E, > Page Basis of java Programming Module-a BPLCK205C S, Constructors + Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. «© Aconstructor initializes an object immediately upon creation. » Ithas the same name as the class in which it resides and is syntactically similar toa method, + Constructors have no return type, not even void. This is because the implicit return ‘type of a class’ constructor is the class type itself. #/ Here, Box uses a constructor to initialize the dinension ef a box class Box t ‘OUTPUT double width; double height; double depth; // This is the constructor for Box Box() { Constructing Box Volume is 1900.8 [Link] .printin(“Canstruéting Box"); } double volume() { return width*height*depth; } , class BoxDeros t public static void main(String args[]) { Box mybox1 = new Sox(); double vol; vol=myboxa .volume(}; [Link] printin(* Volume is:” + vol); + } + new Box() is calling the Box{ ) constructor new. When you do not explicitly define a constructor for a class, then Java creates a default constructor for the class. Prof. Ashwini G Dept of CS&E, MITT Page? Basis of Java Programming Module-3 BPLCK205C Parameterized Constructors * While the Box{ ) constructor in the preceding example does initialize a Box object, itis not very useful—all boxes have the same dimensions. + What is needed is a way to construct Box objects of various dimensions. // Here, Box uses 3 parameterized constructor to initialize the dimension of 3 box class Box t double width; double height; double depth; {/ This is the constructor for Box Box(double w, double h, double d) £ width = w: height depth = 4 t double volume() { return width*height*depth; } class SoxDero7 t public. static void main(String args[]) t Box myboxl = new Box(3,6,9)3 double vol; vol=[Link]{); [Link](™ Volume is:* + vol); + The values 3, 6, and 9 are passed to the Bex{) constructor when new creates the abject. Thus, mybox1’s copy of width, height, and depth will contain the values 3, 6, and 9, respectively. Prof, Ashwini G Dept of (SRE. MITT Page LO Basis of Java Programming Module-3 BPLCK205C 6. The this Keyword + this can be used inside any method to refer to the current object + this refers to the current class instance variable, ## R redundant use of this Box(double w, double h, double d) { [Link] = w this height this. depth } + Inside Box(), this will always refer to the invoking object. While itis redundant in this case, this is usefulin other contexts. = Use of this: D To overcome shadowing or instance variable hiding. 0 To call an overload constructor. (i) Instance Variable Hiding + tis illegal in Java to declare two local variables with the same name inside the same or enclosing scapes. + When a local variable has the same name as an instance variable, the local variable hides the instance variable. if Use this to resolve name-space collisions Box(double width, double height, double depth) { [Link] = width; [Link] = height; [Link] = depth; } 7. Garbage Collection + Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed and their memory released for later reallocation, + Java handles deallocation automatically. The technique that accomplishes this is called garbage collection. « Icworks like this: when no references to an object exist that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. + Garbage collection only occurs sporadically (if at all) during the execution of your program. Prof Ashwini G [Link] CS&E, MITT Page ii Basis of Java Programming Module-3 BPLCK205C 8. The finalize() Method Sometimes an object will need to perform some action when itis destroyed. For example, if an object is holding some non-Java resource such as a file handle or character font. then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. Ik is important to understand that finalize( ) is only called just prior to garbage collection GENERAL FORM protected woid #inalize() i Hf Finalization code here } Here, the keyword protected is a specifier that prevents access to finalize(} by code define outside its class. 9. A Stack Class A-stack stores data using first-in, last-out ordering. stacks are controlled through 2 operation called push and pop. To put an item on tep of the stack, you will use push. To take an item off the stack, you will use pop. J/ This class defines an integer stack that can hold 16 values. class Stack { aint stck{] = new int[ie]; int top; J/ Initialize top-of-stack Stack() { top = +1; } 7/ Push an item onto the stack void push(int item) { af(top==9) [Link]("Stack is full. else stck[++top] = item; } Prof. Ashwini G Dept. of CS&E, MITT Page 12 Basis of Java Programming Module-3 BPLCK205¢ If Pop an item from the stack nce OUTPUT ath eee stack in { mystackl if(top < e) 2 a € ? [Link]( "stack underflew."); 6 return @; 5 4 , 3 else a return stck[tap--]; a } a Stack in } mystack2 class Teststack 48 { 1s 7 v public static void main(String ares{ 1) de { 15 Stack mystackl = new stack(); 14 i 13 Stack mystack2 = new Stack(); ny Q a // push some numbers onto the stack a for(int i-8; 4<18; i++) qe [Link](i); for(int i-18; icde; i++) [Link](i}; /7 pop those numbers off the stack [Link] .printin("Stack in mystack: for(int 4-0; i<18; iss) [Link]. printin(mystackt .pop()); [Link]("Stack in mystack2:"); for(int i-8; i<18; i++) [Link]. print1n([Link]{)); + } Prof, Ashwini G Dept. of CS&E, MITT Page 13 Basis of Java Programming Module-3 BPLCK20SC Chapter 2: A Closer Look at Methods and Classes 1. Overloading Methods + InJava it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. The methods are said to be overloaded, and the process is referred to as method overloading. Condition: 1. Number ofarguments should be different Example: void test (int 2) void test(] 2, Sequence of arguments should be different Example: test (int a, String b) void test (String a, int b) 3. Types of argument should be different Example: void test (int a) void test (String b) + When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. // Demonstrate method overloading. class OverloadDemo OUTPUT { No parameters void test() a: 16 { syst . einen ara), 2 29d br 18 26 1 URRER OWE priMEENC™NO paramere): Golble 9: 128.25 {/ Overload test for one integer parameter. Result: 15198.5625 void test{int a) { [Link]("a: " + a); } U7 Overload test for two integer parameters. void test{int a, int b) 1 + Jf overload test for a double parameter double test(double a) { [Link]("a and b: "+a 4" * +b); [Link]! return at: peintln("double a: " + a); Prof. Ashwini G Dept of CS&E, MITT Page 14 Basis of Java Programming Module-3 BPLCK20S¢ class Overload { public static void main(String ares[]) { OverlosdDemo ab = new Gverloaddemo{); double result; // call all versions of test() [Link](); [Link] (18); [Link](18, 28); result = [Link](123.25); [Link]("Result: * + result); ? ? (i) Overloading Constructors + Im addition to overloading normal methods, you can also overload constructor methods. /* Here, Box defines three constructors to initialize ‘the dimensions of a box various ways. , OUTPUT class Box Volume of myboxl is 3000.8 t Volume of mybox2 is -1.9 double width; Volume of mycube is 343.¢ double height; double depth; /F constructor used when all dimensions specified Box(double w, double h, double d) { width = w height = h; depth = a: } // constructor used when no dimensions specified Box() t width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } Prof, Ashwini G Dept of CSSE, MITT Page 1S Basis of Java Programming Module-3 BPLCK205C J# constructor used when cube is created Box(double len) t width = height = depth = len; } Jf compute and return volume double volume() { return width * height * depth; } } class Overloadtons t public static void main(String args[}) { Jf create boxes using the various constructors Box myboxl = new Box(18, 26, 15); Box mybox2 = new Box(); Box mycube = new Box(7 double vol; Jf get volume of first box vol = [Link](}} [Link]("Volume of mybox1 is /# get volume of second box vol = mybox?.volume(); [Link]("Volume of mybox? is ¢# get volume oF cube vol = [Link](); [Link]("Volume of mycube is + vol); + vol); + vol); 2. Using Objects as Parameters + So far, we have only been using simple types as parameters to methods, However, it is both correct and common to pass objects to methods, + The equals() method inside Test compares two objects for equality and returns the result. = Thatis, it compares the invoking object with the one that itis passed. + lfthey contain the same values, then the method returns true, Otherwise, it returns false, Notice that the parameter o in equals() specifies Test as its type. ——— Prof Ashwini G Dept. of CS&E, MITT Page 16. Basis of Java Programming Moduile-3 BPLCK205C 1 Objects may be passed to methods. class Test t fs int a, bj OUTPUT Test(int i, int 3) obi == ob2: true { ob1 ‘ob3: false // return true if o is equal to the invoking object boolean equals(Test 0) { if(o.a == a 8&8 o.b == b) return true; else return false; } } class Passb t public static void main(String args[]) t Test ob1 = new Test(19@, 22); Test ob2 = new Test(iee, 22); Test ob3 = new Test{-1, -1)5 [Link]("obl == ob2: " + ob .equals(ob2)); [Link]("ob1 == ob3: "+ ob1 .equals(ob3)); ¥ t 3. A Closer Look at Argument Passing + In general, there are two ways that a computer language can pass an argument to a subroutine, +) The first way is call-by-value, This approach copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument, + The second way an argument can be passed is eall-by-reference, In this approach, a reference to an argument (not the value of the argument] is passed to the ‘parameter. — TS, TT OO Prof, Ashwini @ Dept of CSE, MITT Page 17 Basis of Java Programming Module-3 ‘BPLCK205C 4, Returning Objects + A method can return any type of data, including class types that you create, + For example, in the following program, the incrByTen() method returns an object in which the value ofa is ten greater than itis in the invoking object, } { J/ Returning an object. class Test t OUTPUT int a; obl.a: 2 Test(int i) ob2.; az t ob2.a after second increase: 22 + Test incréyTen() { class Retob Test temp = new Test(a+28) ; return temp; } public static void main(String args[]) { Test obl = new Test(2); Test ob; ob2.= obi. inersyten(); Systam,[Link]("ob1.a: ~ + ob1.3); [Link]("ob2.a: ~ + ob2.a); ob2"= [Link]( ); [Link]("ob2.a after second increase: "+0b2.); S. Recursion «Java supports recursion, Recursion is the process of defining something in terms of itself. © Amethod that calls itself is said to be recursive. + The classic example of recursion is the computation of the factorial of a number. + The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 » 2 * 3, or 6, Here is how-a factorial can be computed by use of a recursive method: Prof. Ashwini G Dept of CS&E. MITT Page 18 Basis of Java Programminy Module-3 BPLCK205C /# A simple example of recursion. class Factorial t 1] this is a recursive method int fact(int n) $$. { ‘ourPUT int resul Factorial of 3 is 6 if(nz=1) Factorial of 4 is 24 return 1; Factorial of 5 is 120 result = fact(n-1) * 93 return result; ) } class Recursion t public static void main(String args[I) { Factorial f = new Factorial(); [Link]("factorial-af 3 is " + #.fact(3)); [Link]("Factorial of @ is " + £.fact(4)); [Link]("Factorisl of 5 is ” + #.fact(5)); } } 6. Introducing Access Control + Encapsulation provides another important attribute: access control. * Through encapsulation, you can control what parts of a program can access the members of a class. * By controlling access, you can prevent misuse, For example, allowing access to data only through a well defined set of methods, you can prevent the misuse of that dara. +» Java's access specifiers are default, public, private, and protected. > When we don’t use any keyword explicitly Java will set default access to a given class method. Also called as package-private, which means that all members are visible within the same package but cannot access from other packages } When a member of a class is modified by the public specifier, then that member can be accessed by any ather code, > When a member of class is specified as private, then that member can only be accessed by other members of its class, > protected applies only when inheritance is involved. a Prof Ashwini G Dept. of CS&E, MITT Page 1S Basis of Java Programming Module-3 BPLCK205C J* This program demonstrates the difference between public and private. aj class Test t int aj // default access public int b; // public access private int c; // private access i) methods to access c void sete(int i) t c= dj /f set c's value } int getc() (// get c's value return c; } } class AccessTest { public static void main(String args{]) € Test ob = new Tast(); V0 These are OK, a andib may be sccessed directly ob.a = 10; ob.b = 28; #f This is not OK and will cause an error 7 0b.€ = 3883/7 Error! f/f Nou must access ¢ through its methods [Link](1ee); // OK [Link]("2a, b, and c: " + ob.a + 7 "4 [Link]()); } sab.b + +) Member c is given private access, This means that it cannot be accessed by code outside of its class, + So, inside the AccessTest class, c cannot be used directly, It must be accessed through its public methods: sete } and gete{ }. + If you were to remove the comment symbol from the beginning of the following line, ff ob.c = 108; // Error! Prof, Ashwini G [Link] CS&E, MITT Page 20 Basis of Java Programming Module-3 BPLCK205¢ 7. Understanding static When a member is declared static, it can be accessed before amy objects of its class are created, and without reference to any object ‘You can declare bath methods and variables to be static. The most common example of a static member is main( ). main() is declared as static because it must be called before any abjects exist Instance variables declared as static are, essentially, global variables. When objects of its lass are daclarad, no copy of a static variable is made. Instead allinstances of the class share the same static variable, Methods declared as static have several restr > They can only call other static methods, > They must only access static data, > They cannot refer to this or super in any way //Oenonstrate static variables, methods, and blocks. class UseStatic : ‘OUTPUT auth BSS Static block initialized. static int b; He Ae static void meth(int x) a=3 { [Link]("« =" + x); [Link]("s =“ + a); [Link]("b = " +b); + static { [Link]("Static block initialized.”); baa * a; } public static void main(String args[]) ¢ meth (42); + + To initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded Outside of the class in which they are defined, static methods and variables can be used independently of any object. Page 21 Basis of Java Programming Module- BPLCK205¢ + For example, if you wish to call a static method from outside its class, you can do so using the following general form: classname,methad( ) + Astatic variable can be accessed in the same way—by use of the dot operator on the name of the class, This is how Java implements a controlled version of global methods and global variables 8, Introducing final + A variable can be declared as final, Doing so prevents its contents from being modified. This means that you must initialize a final variable when itis declared, + For example: final int FILE_NEW final int FILE_OPEN final int FILE_SAVE final int FILE_SAVEAS final int FTLE_QUIT + Subsequent parts of your program can now use FILE OPEN, etc. as if they were constants, withoutfear that a value has been changed. + It is a common coding convention to choose all uppercase identifiers for final variables. + Variables declared as final do not occupy memory on a per-instance basis. Thus, a final variable is essentially a constant. + The keyword final can also be applied to methods, but its meaning is substantially different than when it is spplied to variables. 9. Array Revisited + Now that you know about classes, an important point can be made about arrays: they are implemented as objects. + Because of this, there is a special array attribute that you will want to take advantage of. Specifically, the size of an array—that is, the number of elements that an array can hold—is found in its length instance variable. + Allarrays have this variable, and it will always hold the size of the array Prof. Ashwini G Dept of CS&E, MITT Page 22

You might also like