{"id":3444,"date":"2019-06-20T11:42:33","date_gmt":"2019-06-20T11:42:33","guid":{"rendered":"http:\/\/softlect.in\/?p=3444"},"modified":"2019-06-20T11:59:33","modified_gmt":"2019-06-20T11:59:33","slug":"java-classes","status":"publish","type":"post","link":"http:\/\/softlect.com\/index.php\/java-classes\/","title":{"rendered":"Java Classes"},"content":{"rendered":"<h1><a name=\"_Toc179309127\"><\/a><strong>Introducing Classes<\/strong><\/h1>\n<p>&nbsp;<\/p>\n<p>The class is at the core of Java. The class forms the basis for object-oriented programming in Java. Any concept you wish to implement in a Java program must be encapsulated within a class.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309128\"><\/a><strong>Class Fundamentals<\/strong><\/h2>\n<p>The classes created in the preceding chapters primarily exist simply to encapsulate the <strong>main( ) <\/strong>method, which has been used to demonstrate the basics of the Java syntax. Perhaps the most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a <em>template <\/em>for an object, and an object is an <em>instance <\/em>of a class.<\/p>\n<h3><a name=\"_Toc179309129\"><\/a>The General Form of a Class<\/h3>\n<p>When defining a class, declare its exact form and nature. This is done by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or only data, most real-world classes contain both. A class is declared by use of the <strong>class <\/strong>keyword. The general form of a <strong>class <\/strong>definition is shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>class <em>classname <\/em>{<\/p>\n<p><em>type instance-variable1<\/em>;<\/p>\n<p><em>type instance-variable2<\/em>;<\/p>\n<p>\/\/ &#8230;<\/p>\n<p><em>type instance-variableN<\/em>;<\/p>\n<p><em>type methodname1<\/em>(<em>parameter-list<\/em>) {<\/p>\n<p>\/\/ body of method<\/p>\n<p>}<\/p>\n<p><em>type methodname2<\/em>(p<em>arameter-list<\/em>) {<\/p>\n<p>\/\/ body of method<\/p>\n<p>}<\/p>\n<p>\/\/ &#8230;<\/p>\n<p><em>type methodnameN<\/em>(<em>parameter-list<\/em>) {<\/p>\n<p>\/\/ body of method<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>The data, or variables, defined within a <strong>class <\/strong>are called <em>instance variables. <\/em>The code is contained within <em>methods. <\/em>Collectively, the methods and variables defined within a class are called <em>members <\/em>of the class. In most classes, the instance variables are acted upon and accessed by the methods defined for that class. Thus, it is the methods that determine how a class\u2019 data can be used. 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. Java classes do not need to have a <strong>main( ) <\/strong>method. You only specify one if that class is the starting point for your program.<\/p>\n<h3><a name=\"_Toc179309130\"><\/a>A Simple Class<\/h3>\n<p>Here is a class called <strong>Box <\/strong>that defines three instance variables: <strong>width<\/strong>, <strong>height<\/strong>, and <strong>depth<\/strong>. Currently, <strong>Box <\/strong>does not contain any methods.<\/p>\n<p>&nbsp;<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>a class defines a new type of data. In this case, the new data type is called <strong>Box<\/strong>. You will use this name to declare objects of type <strong>Box<\/strong>. It is important to remember that a <strong>class <\/strong>declaration only creates a template; it does not create an actual object. Thus, the preceding code does not cause any objects of type <strong>Box <\/strong>to come into existence. To actually create a <strong>Box <\/strong>object, you will use a statement like the following:<\/p>\n<p>Box mybox = new Box(); \/\/ create a Box object called mybox<\/p>\n<p>&nbsp;<\/p>\n<p>After this statement executes, <strong>mybox <\/strong>will be an instance of <strong>Box<\/strong>. Again, each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. Thus, every <strong>Box <\/strong>object will contain its own copies of the instance variables <strong>width<\/strong>, <strong>height<\/strong>, and <strong>depth<\/strong>. To access these variables, you will use the <em>dot <\/em>(.) operator. The dot operator links the name of the object with the name of an instance variable. For example, to assign the <strong>width <\/strong>variable of <strong>mybox <\/strong>the value 100, you would use the following statement:<\/p>\n<p>&nbsp;<\/p>\n<p>mybox.width = 100;<\/p>\n<p>&nbsp;<\/p>\n<p>This statement tells the compiler to assign the copy of <strong>width <\/strong>that is contained within the <strong>mybox <\/strong>object the value of 100. In general, you use the dot operator to access both the instance variables and the methods within an object. Here is a complete program that uses the <strong>Box <\/strong>class:<\/p>\n<p>&nbsp;<\/p>\n<p>\/* A program that uses the Box class.<\/p>\n<p>Call this file BoxDemo.java<\/p>\n<p>*\/<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>}<\/p>\n<p>\/\/ This class declares an object of type Box.<\/p>\n<p>class BoxDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>Box mybox = new Box();<\/p>\n<p>double vol;<\/p>\n<p>\/\/ assign values to mybox&#8217;s instance variables<\/p>\n<p>mybox.width = 10;<\/p>\n<p>mybox.height = 20;<\/p>\n<p>mybox.depth = 15;<\/p>\n<p>\/\/ compute volume of box<\/p>\n<p>vol = mybox.width * mybox.height * mybox.depth;<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>You should call the file that contains this program <strong>BoxDemo.java<\/strong>, because the <strong>main( ) <\/strong>method is in the class called <strong>BoxDemo<\/strong>, not the class called <strong>Box<\/strong>. When you compile this program, you will find that two <strong>.class <\/strong>files have been created, one for <strong>Box <\/strong>and one for <strong>BoxDemo<\/strong>. The Java compiler automatically puts each class into its own <strong>.class <\/strong>file. It is not necessary for both the <strong>Box <\/strong>and the <strong>BoxDemo <\/strong>class to actually be in the same source file. You could put each class in its own file, called <strong>Box.java <\/strong>and <strong>BoxDemo.java<\/strong>, respectively. To run this program, you must execute <strong>BoxDemo.class<\/strong>. When you do, you will see the following output:<\/p>\n<p>&nbsp;<\/p>\n<p>Volume is 3000.0<\/p>\n<p>&nbsp;<\/p>\n<p>As stated earlier, each object has its own copies of the instance variables. This means that if you have two <strong>Box <\/strong>objects, each has its own copy of <strong>depth<\/strong>, <strong>width<\/strong>, and <strong>height<\/strong>. It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another. For example, the following program declares two <strong>Box <\/strong>objects:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ This program declares two Box objects.<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>}<\/p>\n<p>class BoxDemo2 {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>Box mybox1 = new Box();<\/p>\n<p>Box mybox2 = new Box();<\/p>\n<p>double vol;<\/p>\n<p>\/\/ assign values to mybox1&#8217;s instance variables<\/p>\n<p>mybox1.width = 10;<\/p>\n<p>mybox1.height = 20;<\/p>\n<p>mybox1.depth = 15;<\/p>\n<p>\/* assign different values to mybox2&#8217;s<\/p>\n<p>instance variables *\/<\/p>\n<p>mybox2.width = 3;<\/p>\n<p>mybox2.height = 6;<\/p>\n<p>mybox2.depth = 9;<\/p>\n<p>\/\/ compute volume of first box<\/p>\n<p>vol = mybox1.width * mybox1.height * mybox1.depth;<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>\/\/ compute volume of second box<\/p>\n<p>vol = mybox2.width * mybox2.height * mybox2.depth;<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>The output produced by this program is shown here:<\/p>\n<p>Volume is 3000.0<\/p>\n<p>Volume is 162.0<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309131\"><\/a><strong>Declaring Objects<\/strong><\/h2>\n<p>As just explained, when you create a class, you are creating a new data type. You can use this type to declare objects of that type. However, obtaining objects of a class is a two-step process. First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can <em>refer <\/em>to an object. Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the <strong>new <\/strong>operator. The <strong>new <\/strong>operator dynamically allocates that is, allocates at run time memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by <strong>new<\/strong>. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. the following is used to declare an object of type <strong>Box<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<p>Box mybox = new Box();<\/p>\n<p>&nbsp;<\/p>\n<p>This statement combines the two steps just described. It can be rewritten like this to show each step more clearly:<\/p>\n<p>&nbsp;<\/p>\n<p>Box mybox; \/\/ declare reference to object<\/p>\n<p>mybox = new Box(); \/\/ allocate a Box object<\/p>\n<p>&nbsp;<\/p>\n<p>The first line declares <strong>mybox <\/strong>as a reference to an object of type <strong>Box<\/strong>. After this line executes, <strong>mybox <\/strong>contains the value <strong>null<\/strong>, which indicates that it does not yet point to an actual object. Any attempt to use <strong>mybox <\/strong>at this point will result in a compile-time error. The next line allocates an actual object and assigns a reference to it to <strong>mybox<\/strong>. After the second line executes, you can use <strong>mybox <\/strong>as if it were a <strong>Box <\/strong>object. But in reality, <strong>mybox <\/strong>simply holds the memory address of the actual <strong>Box <\/strong>object. The effect of these two lines of code is depicted in Figure 6-1.<\/p>\n<p>&nbsp;<\/p>\n<h3><a name=\"_Toc179309132\"><\/a>A Closer Look at new<\/h3>\n<p>&nbsp;<\/p>\n<p>As just explained, the <strong>new <\/strong>operator dynamically allocates memory for an object. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p><em>class-var <\/em>= new <em>classname<\/em>( );<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>class-var <\/em>is a variable of the class type being created. The <em>classname <\/em>is the name of the class that is being instantiated. The class name followed by parentheses specifies the <em>constructor <\/em>for the class. A constructor defines what occurs when an object of a class is created. However, if no explicit constructor is specified, then Java will automatically supply a default constructor. This is the case with <strong>Box<\/strong>. It is important to understand that <strong>new <\/strong>allocates memory for an object during run time. The advantage of this approach is that your program can create as many objects as it needs during the execution of your program.\u00a0 A class creates a new data type that can be used to create objects. That is, a class creates a logical framework that defines the relationship between its members. When you declare an object of a class, you are creating an instance of that class. Thus, a class is a logical construct. An object has physical reality and an object occupies space in memory.<\/p>\n<h3><a name=\"_Toc179309133\"><\/a>Assigning Object Reference Variables<\/h3>\n<p>For example:<\/p>\n<p>&nbsp;<\/p>\n<p>Box b1 = new Box();<\/p>\n<p>Box b2 = b1;<\/p>\n<p>&nbsp;<\/p>\n<p>after this executes, <strong>b1 <\/strong>and <strong>b2 <\/strong>will both refer to the <em>same <\/em>object. The assignment of <strong>b1 <\/strong>to <strong>b2 <\/strong>did not allocate any memory or copy any part of the original object. It simply makes <strong>b2 <\/strong>refer to the same object as does <strong>b1<\/strong>. Thus, any changes made to the object through <strong>b2 <\/strong>will affect the object to which <strong>b1 <\/strong>is referring, since they are the same object. \u00a0Look at the other example:<\/p>\n<p>&nbsp;<\/p>\n<p>Box b1 = new Box();<\/p>\n<p>Box b2 = b1;<\/p>\n<p>\/\/ &#8230;<\/p>\n<p>b1 = null;<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <strong>b1 <\/strong>has been set to <strong>null<\/strong>, but <strong>b2 <\/strong>still points to the original object. <em>When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.<\/em><\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309134\"><\/a><strong>Introducing Methods<\/strong><\/h2>\n<p>&nbsp;<\/p>\n<p>Classes usually consist of two things: instance variables and methods. This is the general form of a method:<\/p>\n<p>&nbsp;<\/p>\n<p><em>type name<\/em>(<em>parameter<\/em>&#8211;<em>list<\/em>) {<\/p>\n<p>\/\/ body of method<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>type <\/em>specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be <strong>void<\/strong>. The name of the method is specified by <em>name. <\/em>This can be any legal identifier other than those already used by other items. The <em>parameter-list <\/em>is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the <em>arguments <\/em>passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Methods that have a return type other than <strong>void <\/strong>return a value to the calling method using the following form of the <strong>return <\/strong>statement:<\/p>\n<p>&nbsp;<\/p>\n<p>return <em>value<\/em>;<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>value <\/em>is the value returned.<\/p>\n<h3><a name=\"_Toc179309135\"><\/a>Adding a Method to the Box Class<\/h3>\n<p>&nbsp;<\/p>\n<p>Although it is perfectly fine to create a class that contains only data. Most of the time you will use methods to access the instance variables defined by the class. In addition to defining methods that provide access to data, you can also define methods that are used internally by the class itself. Let\u2019s begin by adding a method to the <strong>Box <\/strong>class. since the volume of a box is dependent upon the size of the box, it makes sense to have the <strong>Box <\/strong>class compute it. To do this, you must add a method to <strong>Box<\/strong>, as shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ This program includes a method inside the box class.<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>\/\/ display volume of a box<\/p>\n<p>void volume() {<\/p>\n<p>System.out.print(&#8220;Volume is &#8220;);<\/p>\n<p>System.out.println(width * height * depth);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class BoxDemo3 {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>Box mybox1 = new Box();<\/p>\n<p>Box mybox2 = new Box();<\/p>\n<p>\/\/ assign values to mybox1&#8217;s instance variables<\/p>\n<p>mybox1.width = 10;<\/p>\n<p>mybox1.height = 20;<\/p>\n<p>mybox1.depth = 15;<\/p>\n<p>\/* assign different values to mybox2&#8217;s<\/p>\n<p>instance variables *\/<\/p>\n<p>mybox2.width = 3;<\/p>\n<p>mybox2.height = 6;<\/p>\n<p>mybox2.depth = 9;<\/p>\n<p>\/\/ display volume of first box<\/p>\n<p>mybox1.volume();<\/p>\n<p>\/\/ display volume of second box<\/p>\n<p>mybox2.volume();<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>This program generates the following output, which is the same as the previous version.<\/p>\n<p>Volume is 3000.0<\/p>\n<p>Volume is 162.0<\/p>\n<p>&nbsp;<\/p>\n<p>Look closely at the following two lines of code:<\/p>\n<p>mybox1.volume();<\/p>\n<p>mybox2.volume();<\/p>\n<p>&nbsp;<\/p>\n<p>The first line here invokes the <strong>volume( ) <\/strong>method on <strong>mybox1<\/strong>. That is, it calls <strong>volume( ) <\/strong>relative to the <strong>mybox1 <\/strong>object, using the object\u2019s name followed by the dot operator. Thus, the call to <strong>mybox1.volume( ) <\/strong>displays the volume of the box defined by <strong>mybox1<\/strong>, and the call to <strong>mybox2.volume( ) <\/strong>displays the volume of the box defined by <strong>mybox2<\/strong>. Each time <strong>volume( ) <\/strong>is invoked, it displays the volume for the specified box. After the statements inside <strong>volume( ) <\/strong>have executed, control is returned to the calling routine, and execution resumes with the line of code following the call. There is something very important to notice inside the <strong>volume( ) <\/strong>method: the instance variables <strong>width<\/strong>, <strong>height<\/strong>, and <strong>depth <\/strong>are referred to directly, without preceding them with an object name or the dot operator. When a method uses an instance variable that is defined by its class, it does so directly, without explicit reference to an object and without use of the dot operator.\u00a0 A method is always invoked relative to some object of its class. Once this invocation has occurred, the object is known. This means that <strong>width<\/strong>, <strong>height<\/strong>, and <strong>depth <\/strong>inside <strong>volume( ) <\/strong>implicitly refer to the copies of those variables found in the object that invokes <strong>volume( )<\/strong>.<\/p>\n<h3><a name=\"_Toc179309136\"><\/a>Returning a Value<\/h3>\n<p>&nbsp;<\/p>\n<p>While the implementation of <strong>volume( ) <\/strong>does move the computation of a box\u2019s volume inside the <strong>Box <\/strong>class where it belongs, it is not the best way to do it. A better way to implement <strong>volume( ) <\/strong>is to have it compute the volume of the box and return the result to the caller. The following example does just that:<\/p>\n<p>\/\/ Now, volume() returns the volume of a box.<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>\/\/ compute and return volume<\/p>\n<p>double volume() {<\/p>\n<p>return width * height * depth;<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class BoxDemo4 {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>Box mybox1 = new Box();<\/p>\n<p>Box mybox2 = new Box();<\/p>\n<p>double vol;<\/p>\n<p>\/\/ assign values to mybox1&#8217;s instance variables<\/p>\n<p>mybox1.width = 10;<\/p>\n<p>mybox1.height = 20;<\/p>\n<p>mybox1.depth = 15;<\/p>\n<p>\/* assign different values to mybox2&#8217;s<\/p>\n<p>instance variables *\/<\/p>\n<p>mybox2.width = 3;<\/p>\n<p>mybox2.height = 6;<\/p>\n<p>mybox2.depth = 9;<\/p>\n<p>\/\/ get volume of first box<\/p>\n<p>vol = mybox1.volume();<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>\/\/ get volume of second box<\/p>\n<p>vol = mybox2.volume();<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, when <strong>volume( ) <\/strong>is called, it is put on the right side of an assignment statement. On the left is a variable, in this case <strong>vol<\/strong>, that will receive the value returned by <strong>volume( )<\/strong>. Thus, after<\/p>\n<p>&nbsp;<\/p>\n<p>vol = mybox1.volume();<\/p>\n<p>&nbsp;<\/p>\n<p>executes, the value of <strong>mybox1.volume( ) <\/strong>is 3,000 and this value then is stored in <strong>vol<\/strong>. There are two important things to understand about returning values:<\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>The type of data returned by a method must be compatible with the return type specified by the method. For example, if the return type of some method is <strong>boolean<\/strong>, you could not return an integer.<\/li>\n<li>The variable receiving the value returned by a method such as <strong>vol<\/strong>, in this case must also be compatible with the return type specified for the method.<\/li>\n<\/ul>\n<h3><a name=\"_Toc179309137\"><\/a>Adding a Method That Takes Parameters<\/h3>\n<p>&nbsp;<\/p>\n<p>Parameters allow a method to be generalized. That is, a parameterized method can operate on a variety of data and\/or be used in a number of slightly different situations. Here is a method that returns the square of the number 10:<\/p>\n<p>&nbsp;<\/p>\n<p>int square()<\/p>\n<p>{<\/p>\n<p>return 10 * 10;<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>While this method return the value of 10 squared. However, if you modify the method so that it takes a parameter, as shown next, then you can make <strong>square( ) <\/strong>much more useful.<\/p>\n<p>int square(int i)<\/p>\n<p>{<\/p>\n<p>return i * i;<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>Now, <strong>square( ) <\/strong>will return the square of whatever value it is called with. That is, <strong>square( ) <\/strong>is now a general-purpose method that can compute the square of any integer value, rather than just 10. Here is an example:<\/p>\n<p>&nbsp;<\/p>\n<p>int x, y;<\/p>\n<p>x = square(5); \/\/ x equals 25<\/p>\n<p>x = square(9); \/\/ x equals 81<\/p>\n<p>y = 2;<\/p>\n<p>x = square(y); \/\/ x equals 4<\/p>\n<p>&nbsp;<\/p>\n<p>In the first call to <strong>square( )<\/strong>, the value 5 will be passed into parameter <strong>i<\/strong>. In the second call, <strong>i <\/strong>will receive the value 9. The third invocation passes the value of <strong>y<\/strong>, which is 2 in this example. As these examples show, <strong>square( ) <\/strong>is able to return the square of whatever data it is passed. It is important to keep the two terms <em>parameter <\/em>and <em>argument <\/em>straight. A <em>parameter <\/em>is a variable defined by a method that receives a value when the method is called. For example, in <strong>square( )<\/strong>, <strong>i <\/strong>is a parameter. An <em>argument <\/em>is a value that is passed to a method when it is invoked. For example, <strong>square(100) <\/strong>passes 100 as an argument. Inside <strong>square( )<\/strong>, the parameter <strong>i <\/strong>receives that value. Thus, a better approach to setting the dimensions of a box is to create a method that takes the dimension of a box in its parameters and sets each instance variable appropriately. This concept is implemented by the following program:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ This program uses a parameterized method.<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>\/\/ compute and return volume<\/p>\n<p>double volume() {<\/p>\n<p>return width * height * depth;<\/p>\n<p>}<\/p>\n<p>\/\/ sets dimensions of box<\/p>\n<p>void setDim(double w, double h, double d) {<\/p>\n<p>width = w;<\/p>\n<p>height = h;<\/p>\n<p>depth = d;<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class BoxDemo5 {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>Box mybox1 = new Box();<\/p>\n<p>Box mybox2 = new Box();<\/p>\n<p>double vol;<\/p>\n<p>\/\/ initialize each box<\/p>\n<p>mybox1.setDim(10, 20, 15);<\/p>\n<p>mybox2.setDim(3, 6, 9);<\/p>\n<p>\/\/ get volume of first box<\/p>\n<p>vol = mybox1.volume();<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>\/\/ get volume of second box<\/p>\n<p>vol = mybox2.volume();<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, the <strong>setDim( ) <\/strong>method is used to set the dimensions of each box. For example, when mybox1.setDim(10, 20, 15); is executed, 10 is copied into parameter <strong>w<\/strong>, 20 is copied into <strong>h<\/strong>, and 15 is copied into <strong>d<\/strong>. Inside <strong>setDim( ) <\/strong>the values of <strong>w<\/strong>, <strong>h<\/strong>, and <strong>d <\/strong>are then assigned to <strong>width<\/strong>, <strong>height<\/strong>, and <strong>depth<\/strong>, respectively.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309138\"><\/a><strong>Constructors<\/strong><\/h2>\n<p>&nbsp;<\/p>\n<p>Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. A <em>constructor <\/em>initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the <strong>new <\/strong>operator completes. Constructors have no return type, not even <strong>void<\/strong>. This is because its is called implicitly or automatically. You can rework the <strong>Box <\/strong>example so that the dimensions of a box are automatically initialized when an object is constructed. This version shows constructors:<\/p>\n<p>&nbsp;<\/p>\n<p>\/* Here, Box uses a constructor to initialize the<\/p>\n<p>dimensions of a box.<\/p>\n<p>*\/<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>\/\/ This is the constructor for Box.<\/p>\n<p>Box() {<\/p>\n<p>System.out.println(&#8220;Constructing Box&#8221;);<\/p>\n<p>width = 10;<\/p>\n<p>height = 10;<\/p>\n<p>depth = 10;<\/p>\n<p>}<\/p>\n<p>\/\/ compute and return volume<\/p>\n<p>double volume() {<\/p>\n<p>return width * height * depth;<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class BoxDemo6 {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>\/\/ declare, allocate, and initialize Box objects<\/p>\n<p>Box mybox1 = new Box();<\/p>\n<p>Box mybox2 = new Box();<\/p>\n<p>double vol;<\/p>\n<p>\/\/ get volume of first box<\/p>\n<p>vol = mybox1.volume();<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>\/\/ get volume of second box<\/p>\n<p>vol = mybox2.volume();<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>When this program is run, it generates the following results:<\/p>\n<p>Constructing Box<\/p>\n<p>Constructing Box<\/p>\n<p>Volume is 1000.0<\/p>\n<p>Volume is 1000.0<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, both <strong>mybox1 <\/strong>and <strong>mybox2 <\/strong>were initialized by the <strong>Box( ) <\/strong>constructor when they were created. Since the constructor gives all boxes the same dimensions, 10 by 10 by 10, both <strong>mybox1 <\/strong>and <strong>mybox2 <\/strong>will have the same volume.\u00a0 As you know, when you allocate an object, you use the following general form:<\/p>\n<p>&nbsp;<\/p>\n<p><em>class-var <\/em>= new <em>classname<\/em>( );<\/p>\n<p>&nbsp;<\/p>\n<p>Now you can understand why the parentheses are needed after the class name. What is actually happening is that the constructor for the class is being called. Thus, in the line<\/p>\n<p>&nbsp;<\/p>\n<p>Box mybox1 = new Box();<\/p>\n<p><strong>\u00a0<\/strong><\/p>\n<p><strong>new Box( ) <\/strong>is calling the <strong>Box( ) <\/strong>constructor. When you do not explicitly define a constructor for a class, then Java creates a default constructor for the class. This is why the preceding line of code worked in earlier versions of <strong>Box <\/strong>that did not define a constructor. The default constructor automatically initializes all instance variables to zero. Once you define your own constructor, the default constructor is no longer used.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309139\"><\/a><strong>Parameterized Constructors<\/strong><\/h2>\n<p>&nbsp;<\/p>\n<p>While the <strong>Box( ) <\/strong>constructor in the preceding example does initialize a <strong>Box <\/strong>object, it is not very useful since all boxes have the same dimensions. What is needed is a way to construct <strong>Box <\/strong>objects of various dimensions. The easy solution is to add parameters to the constructor. For example, the following version of <strong>Box <\/strong>defines a parameterized constructor which sets the dimensions of a box as specified by those parameters. For example:<\/p>\n<p>&nbsp;<\/p>\n<p>\/* Here, Box uses a parameterized constructor to<\/p>\n<p>initialize the dimensions of a box.<\/p>\n<p>*\/<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>\/\/ This is the constructor for Box.<\/p>\n<p>Box(double w, double h, double d) {<\/p>\n<p>width = w;<\/p>\n<p>height = h;<\/p>\n<p>depth = d;<\/p>\n<p>}<\/p>\n<p>\/\/ compute and return volume<\/p>\n<p>double volume() {<\/p>\n<p>return width * height * depth;<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class BoxDemo7 {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>\/\/ declare, allocate, and initialize Box objects<\/p>\n<p>Box mybox1 = new Box(10, 20, 15);<\/p>\n<p>Box mybox2 = new Box(3, 6, 9);<\/p>\n<p>double vol;<\/p>\n<p>\/\/ get volume of first box<\/p>\n<p>vol = mybox1.volume();<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>\/\/ get volume of second box<\/p>\n<p>vol = mybox2.volume();<\/p>\n<p>System.out.println(&#8220;Volume is &#8221; + vol);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>The output from this program is shown here:<\/p>\n<p>Volume is 3000.0<\/p>\n<p>Volume is 162.0<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, each object is initialized as specified in the parameters to its constructor. For example, in the following line,<\/p>\n<p>&nbsp;<\/p>\n<p>Box mybox1 = new Box(10, 20, 15);<\/p>\n<p>&nbsp;<\/p>\n<p>the values 10, 20, and 15 are passed to the <strong>Box( ) <\/strong>constructor when <strong>new <\/strong>creates the object. Thus, <strong>mybox1<\/strong>\u2019s copy of <strong>width<\/strong>, <strong>height<\/strong>, and <strong>depth <\/strong>will contain the values 10, 20, and 15, respectively.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309140\"><\/a><strong>The this Keyword<\/strong><\/h2>\n<p>&nbsp;<\/p>\n<p>Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the <strong>this <\/strong>keyword. <strong>this <\/strong>can be used inside any method to refer to the <em>current <\/em>object. That is, <strong>this <\/strong>is always a reference to the object on which the method was invoked. You can use <strong>this <\/strong>anywhere a reference to an object of the current class\u2019 type is permitted. consider the following version of <strong>Box( )<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ A redundant use of this.<\/p>\n<p>Box(double w, double h, double d) {<\/p>\n<p>this.width = w;<\/p>\n<p>this.height = h;<\/p>\n<p>this.depth = d;<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>This version of <strong>Box( ) <\/strong>operates exactly like the earlier version. The use of <strong>this <\/strong>is redundant, but perfectly correct. Inside <strong>Box( )<\/strong>, <strong>this <\/strong>will always refer to the invoking object.<\/p>\n<h3><a name=\"_Toc179309141\"><\/a>Instance Variable Hiding<\/h3>\n<p>&nbsp;<\/p>\n<p>you can have local variables, including parameters to methods, which overlap with the names of the class\u2019 instance variables. However, when a local variable has the same name as an instance variable, the local variable <em>hides <\/em>the instance variable. This is why <strong>width<\/strong>, <strong>height<\/strong>, and <strong>depth <\/strong>were not used as the names of the parameters to the <strong>Box( ) <\/strong>constructor inside the <strong>Box <\/strong>class. Because <strong>this <\/strong>lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables. For example, here is another version of <strong>Box( )<\/strong>, which uses <strong>width<\/strong>, <strong>height<\/strong>, and <strong>depth <\/strong>for parameter names and then uses <strong>this <\/strong>to access the instance variables by the same name:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Use this to resolve name-space collisions.<\/p>\n<p>Box(double width, double height, double depth) {<\/p>\n<p>this.width = width;<\/p>\n<p>this.height = height;<\/p>\n<p>this.depth = depth;<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309142\"><\/a><strong>Garbage Collection<\/strong><\/h2>\n<p>&nbsp;<\/p>\n<p>Since objects are dynamically allocated by using the <strong>new <\/strong>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 <em>garbage collection. <\/em>\u00a0when 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 periodically during the execution of your program.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309143\"><\/a><strong>The finalize( ) Method<\/strong><\/h2>\n<p>&nbsp;<\/p>\n<p>Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding resource such as a file, 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 <em>finalization. <\/em>By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. To add a finalizer to a class, you simply define the <strong>finalize( ) <\/strong>method. The Java run time calls that method whenever it is about to recycle an object of that class. Inside the <strong>finalize( ) <\/strong>method you will specify those actions that must be performed before an object is destroyed. The garbage collector runs periodically, checking for objects that are no longer referenced by any running state. The <strong>finalize( ) <\/strong>method has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>protected void finalize( )<\/p>\n<p>{<\/p>\n<p>\/\/ finalization code here<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>Here, the keyword <strong>protected <\/strong>is a specifier that prevents access to <strong>finalize( ) <\/strong>by code defined outside its class. It is important to understand that <strong>finalize( ) <\/strong>is only called just prior to garbage collection. It is not called when an object goes out-of-scope. <em>Java does not support this idea of destructors. The <strong>finalize( ) <\/strong>method only approximates the function of a destructor.<\/em><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introducing Classes &nbsp; The class is at the core of Java. The class forms the basis for object-oriented programming in Java. Any concept you wish to implement in a Java&hellip; <\/p>\n","protected":false},"author":1,"featured_media":3476,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[83],"tags":[],"aioseo_notices":[],"amp_enabled":true,"_links":{"self":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3444"}],"collection":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/comments?post=3444"}],"version-history":[{"count":2,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3444\/revisions"}],"predecessor-version":[{"id":3483,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3444\/revisions\/3483"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/media\/3476"}],"wp:attachment":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/media?parent=3444"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/categories?post=3444"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/tags?post=3444"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}