280 likes | 297 Views
//This progam includes a method inside the box class. class Box { Box is new data type of the class. double width; double height; Box is used to declare objects for this type double dept h ; Class declaration only create s a template , not object
E N D
//This progam includes a method inside the box class. class Box {Box is new data type of the class. double width; double height;Box is used to declare objects for this type double depth;Class declaration only creates a template, not object //display volume a boxThis code does not cause any objects of type Box void volume ( ) { System.out.print (“Volume is”); System.out.println(width*height*depth); } } class BoxDemo3 { public static void main (String args [ ]) { Box mybox1 = new Box( );After this statement executes, mybox1 Box mybox2 = new Box ( );and mybox2 will be instances of Box // assign values to mybox1’s instance variables mybox1.width=10; mybox1.height=20; mybox1.depth=15; //assign different values to mybox2’ s instance variables mybox2.width=3; mybox2.height=6; mybox2.depth=9; //display volume of first and second boxes mybox1.volume();Invokes volume( ) method on mybox1 mybox2.volume();Invokes volume ( ) method on mybox1 } }volume () method is called relative to the mybox1 or mybox2 object,
Calling a Method • When mybox1.volume() method is executed Java run time system transfers control to the code defined inside volume(). • After the statements inside volume ( ) have executed, • control is returned to the volume ( ) calling routine, and • execution resumes with the line of code following that call. • Instance variables width, height, depth inside volume() method are referred to directly, • without explicit reference to an object • without use of the dot operator.
Important: • A method is always invoked relative to some object of its class • Once this invocation has occurred, the object is known. • Thus, within this method, there is no need to specify the object a second time. • This means that width, height, and depth inside volume() implicitly refer to the copies of those variables found in the object that invokes volume(). As summary: • When instance variable is accessed by code that a part of the same class as the instance variable, that variable can be referred to directly. On the contrary: • When the instance variable is accessed by code, that is not part of the class in which the instance variable is defined, • it must be done through an object, by use of the dot operator.
Adding a Method that Takes Parameters • While some methods don’t need parameters, most do. • Parameters allow a method to be generalized. • A parameterized method can operate on a variety of dataand/or be used in a number of slightly different situations. int square () { return 10*10; } • If we modify the method, it takes a parameter int square (int i) { return i*i; } • Square is now a general-purpose method that can compute the square of any integer value. • Now square will return the square of whatever value it is called with. int x,y; x=square(5); //x equals 25 x=square (9); // x equals 81 y=2; x=square(y); //x equals 4
The Previous Program Using a Parameterized Method class Box { double width; double height; double depth; //compute and return a value double volume ( ) { return width*height*depth; } //sets dimensions of box void setDim(double w, double h, double d) { width = w; A better approach to setting the dimensions of a box is to height =h; create a method that takes the dimension of a box in its depth =d; parameters and sets each instance variable appropriately } } class BoxDemo4 { public static void main (String args [ ]) { Box mybox1 = new Box( ); Box mybox2 = new Box ( ); double vol; //initialize each box mybox1.setDim (10,20,15); mybox2.setDim( 3,6,9); //get volume each box vol =mybox1.volume(); System.out.println (“Volume is” + vol); vol =mybox2.volume(); System.out.println (“Volume is” + vol); } }
Constructors • Objects are allocated by specifying the new operator with an object constructor • A constructor is a special method with the same name as its class and return no type, it is not void even. • Because the implicit return type of a class constructor is the class type itself • It’s called when a new class instance is created. • It initializes all of the variables in a class each time an instance is created. • Once defined, it is automatically called after the object is created, before new operator completes. • We can rework the Box example so that the dimensions of a box are automatically initialized when an object is constructed. To do so, replacesetDim() with a constructor.
Box uses a constructor to initialize the dimensions of a box class Box { double width; double height; double depth; //This is the constructor for Box. Box() { System.out.println (“Constructing Box”); width = 10; height =10; depth =10; } //compute and returm volume double volume ( ) { return width*height*depth; } } class BoxDemo5 { public static void main (String args [ ]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box( );mybox1 and mybox2 were initialized by the Box() Box mybox2 = new Box ( ) ; constructor when they were created. double vol; Since the constructor gives all boxes the same //get volume each box dimensions, both mybox1 and mybox2 will have vol =mybox1.volume() ; same value as follows: System.out.println (“Volume is” + vol); vol =mybox2.volume(); Constructing Box The println() statement inside Box() System.out.println (“Volume is” + vol); Constructing Box is for sake of illustration only.Most } Volume is 1000.0 Most constructor functions will not }Volume is 1000.0display anything.
Box uses a parameterized constructor to initialize the dimensions of a box class Box ( ) { double width; double height; double depth; //This is the constructor for Box. Box(double w, double h, double d) { We construct the Box objects of various width = w; dimensions by adding parameters to constructor height =h; depth =d; } //compute and returm volume double volume ( ) { return width*height*depth; } } class BoxDemo6 { public static void main (String args [ ]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10,20,15 );The values 10,25,and 15 are passed to the Box mybox2 = new Box (3,6,9 ) ; Box() constructor when new creates object double vol; Thus mybox1’s copy of width, height, and depth will //get volume each box contain the values 10,20,and 25 respectively vol =mybox1.volume() ; System.out.println (“Volume is” + vol); vol =mybox2.volume();The output from this program is: System.out.println (“Volume is” + vol); }Volume is 3000.0 }Volume is 162.0
The this Keyword • Sometimes a method will need to refer to the object that invoked it. • To allow this, java defines the this keyword. • this can be used inside any method to refer to the current object. • That is, this is always a reference to the object on which the method was invoked. • We can use this anywhere a reference to an object of the current class’ type is permitted. //A redundant use of this. Box (double w, double h, double d) { this.width= w; this.height= h; this.depth=d; } • Although the use of this is redundant above , it is perfectly correct.
Instance and Local Variables • Instance Variables are declared inside the braces of the class definition, but not inside any particular method in that class. • Because they belong to entire class, and copies of them appear in any of the methods inside their class. • They set to a default value 0 (for numeric types), false (for boolean variables , or null(for class type variables) unless they are initialized • Instance variable differ from method arguments and other variables that are declared inside a single method.These variables are called local variables including formal parameters to methods, which overlap with names of class’ instance variables. • Local variables are effectively private variables that can be seen only by code inside the method. • Java does not initialize local variables, so the values must be assignedby the user. • Local variables live only as long as the method is executingand then they disappear. • Each time the method is invokes, its local variables are created and must be assigned values
Instance Variable Hiding • When a local variable has the same name as an instance variable, the local variable hides the instance variables. • This is why width, height, and depth were not used as the names of the parameters to the Box() constructor inside the Box class in the previous example. • If they had been, then width would have referred to the formal parameter, hiding the instance variable width. • It is usually easier to use different names to the problem • Moreover, this lets us refer directly to the object • So we can use this to resolve any name space collisions that might occur between instance and local variables. box (double width, double height, double depth) { this.width = width; this.height= height; this.depth= depth; }
Garbage Collection • Objects are dynamically allocated by using new operator. • In C we don’t have to do anything to get rid of objects • In C++ , dynamically allocated objects are manually released by use of a delete operator. • Java runtime system uses a garbage collection mechanism to deal with objects no longer in user. • The garbage collector sweeps up objects not referenced by any variables and removes them from memory. • Garbage collection is one of the most important features of Java. • It frees us from the errorprone task of having to worry about details memory allocation and deallocation.
The finalize () Method • It is a reserved method name • finalize () method is called when an object is no longer being used, i.e. when there are no further references to it • To add a finalizer method to a class, we simply define the finalize () method. • The Java run time calls that method protected void finalize() { //finalization code here } • The keyword protected is a specifier that prevents access to this method by code defined outside its class • It is important to understand that finalize() is only called just prior to garbage collection. • This means that we cannot knowwhen the finalize() method will be executed.
The difference of finalize() method with a destructor in C++ • C++ allows us to define a destructor for a class, which is called when an object goes out of scope. • Java does not support this idea or provide for destructors. • The finalize method only approximates the function of a destructor.
Summarizing the Encapsulation Achieved by Java • By creating a class, we create a new data type • Defining both the nature of data being manipulated and the routines used to manipulate it. • Methods define a consistent and controlled interface to class’s data • A class is like a data engine • No knowledge of what goes on inside the engine is required to use the engine through its controls • The details are hidden, its inner workings can be changed as needed • As long as the code uses the class through its methods, internal details can change without causing side effects outside the class.
A Stack Class to Summarize the Encapsulation Achieved by Java • Stack is one of the classic examples of encapsulation. • Stores data using first in, last out ordering. • The first plate(like a stack of plates on a table) put down on the table is the last plate to be used. • Stacks are controlled through two operations called push and pop. • To put an item on top of the stack, we use push • To take an item off the stack we use pop. • Next slide shows the implementation a stack defining an integer stack that can hold 10 integers
classStack {The stack class defines two data items and three methods. int stck [ ] = new int [10]; The stack of integers is held by the array stck. This array is int tos; indexed by the variable tos, which always contains the index of the top of the stack //Initialize top-of- stack Stack () { The Stack constructor initializes tos to -1, which indicates tos = -1; an empty stack } //Push an item onto the stack void push (int item) { The method push puts an item on the stack if( tos == 9) System.out.println (“Stack is full”); else stck [++tos] = item; } //Pop an item from the stack int pop() { To retrieve an item, call pop() if (tos < 0) { System.out.println (“Stack underflow”); Since access to the stack is through return 0; push() and pop(), the fact that the stack } is held is actually not relevant to using else stack. Stack can be held in a more return stck [tos---]; complicated data structure., such as a linked list } }
The class TestStack demonstratesthe Stack class. • It creates twointegerstacks, pushes somevalues onto each , thenpops them off class TextStack{ public static void main (String args[] ) { Stack mystack1= new Stack(); Stack mystack2 = new Stack(); //push some numbers onto the stack for ( int i =0; i<10; i++)mystack1.push(i); for ( int i =10; i<20; i++) mystack2.push(i); //pop those numbers off the stack System.out.println(“Stack mystack1:”); for (int i=0; i<10; i++) System.out.println (mystack1.pop()); System.out.println(“Stack mystack2:”); for (int i=0; i<10; i++) System.out.println (mystack2.pop()); } }
Program generates the following output • C:\JBUILDER8\JDK1.4\bin\javaw -classpath "C:\WINDOWS\jbproject\TextStack\classes;C:\JBUILDER8\JDK1.4\JRE\lib\rt.jar;C:\JBUILDER8\JDK1.4\JRE\lib\i18n.jar;C:\JBUILDER8\JDK1.4\JRE\lib\sunrsasign.jar;C:\JBUILDER8\JDK1.4\JRE\lib\jsse.jar;C:\JBUILDER8\JDK1.4\JRE\lib\jce.jar;C:\JBUILDER8\JDK1.4\JRE\lib\charsets.jar;C:\JBUILDER8\JDK1.4\JRE\classes;C:\JBUILDER8\jdk1.4\lib\tools.jar" textstack.TextStack Stack mystack1: 9 8 7 6 5 4 3 2 1 0 Stack mystack2: 19 18 17 16 15 14 13 12 11 10 • As we can see, the contents of each stack are separate.
Language Fundamentals I • Identifiers are names of variables, functions, classes etc. • The name used as an identifier must follow the following rules in Java technology. • Each character is either a digit, letter, underscore(_) or currency symbol ($,¢, £ or ¥) • First character cannot be a digit. • The identifier name must not be a reserved word.
Language Fundamentals II • A keyword or reserved word in Java technology has special meaning and cannot be used as a user defined identifier. • It is important to understand that Java language is case-sensitive. So even though super is a keyword, Super is not. • All the Java technology keywords are in lower case • The list of keywords in Java technology is given below:
Language Fundamentals III • A literal in Java technology denotes a constant value. For example; • 0 is an integer literal, and 'c' is a character literal. • The reserved literals true and false are used to represent boolean literals. • "This is a string" is a string literal. • Integer literals can also be specified as octal (base 8), or hexadecimal (base 16). • Octal and hexadecimal have 0 and 0x prefix respectively. • So 03 and 0x3 are representation of integer three in octal and hexa-decimal respectively.
Language Fundamentals IV • Java technology supports three type of comments: • A single line comment starting with // • A multi-line comment enclosed between /* and */ • A documentation or javadoc comment is enclosed between /** and */. • These comments can be used to generate HTML documents using the javadoc utility, which is part of Java language.
Language Fundamentals V • Java technology supports the following primitive types: • boolean (for representing true or false), • a character type called char, • four integer types (byte, short, int and long) • two floating point types (float and double)
Language Fundamentals VI • Corresponding to all the primitive type there is a wrapper class defined. • These classes provide useful methods for manipulating primitive data values and objects.
Language Fundamentals VII • Instance variables (data members of a class) and static variables are initialized to default values. • Local variables (i.e. variables defined in blocks or inside member functions) are not initialized to default values. • Local variables must be explicitly initialized before they are used. • If local variables are used before initialization, compilation error gets generated. • The defaults for static and instance variables are given in the table below.
Language Fundamentals VIII • The defaults for static and instance variables are given in the table below: public static void main(String args[]) { int i; System.out.println(i);} Printing of i generates a compilation error, because local variablei is usedbefore being initialized. The initialization of instance and static variables is an important concept both for understanding of Java.