Take the object as the parameter-general Linux technology-Linux programming and kernel information. The following is a detailed description. So far, we have used simple types as method parameters. However, it is also common to pass objects to Methods correctly. For example, consider the following simple program:
// Objects may be passed to methods. class Test {int a, B;
Test (int I, int j) {a = I; B = j;
}
// Return true if o is equal to the invoking object
Boolean equals (Test o ){
If (o. a = a & o. B = B) return true;
Else return false;
}
}
Class PassOb {
Public static void main (String args []) {Test ob1 = new Test (100,22); Test ob2 = new Test (100,22); Test ob3 = new Test (-1, -1 );
In this program, the equals () method in Test compares the equality of two objects and returns the comparison result. That is, it compares the called object with the passed object. If they contain the same values, the return value of this method is true. Otherwise, the return value is false. Note that the independent variable o in equals specifies Test as its type. Although Test is the type of the class created in the program, it uses the same built-in type as Java.
The most common use of object parameters involves constructors. You often want to construct a new object and make its initial state the same as that of some existing objects. To do this, you must define a constructor that uses an object as a parameter of its class. For example, the following Box version allows an object to initialize another object:
// Here, Box allows one object to initialize another.
Class Box {double width; double height; double depth;
Public static void main (String args []) {// create boxes using the varous constructorsBox mybox1 = new Box (10, 20, 15); Box mybox2 = new Box (); box mycube = new Box (7 );
Box myclone = new Box (mybox1 );
Double vol;
// Get volume of first box
Vol = mybox1.volume ();
System. out. println ("Volume of mybox1 is" + vol );
// Get volume of second box
Vol = mybox2.volume ();
System. out. println ("Volume of mybox2 is" + vol );
// Get volume of cube
Vol = mycube. volume ();
System. out. println ("Volume of cube is" + vol );
// Get volume of clone
Vol = myclone. volume ();
System. out. println ("Volume of clone is" + vol );
}
}
In this program, you can see that when you start to create your own class, in order to facilitate efficient object construction, you must provide multiple forms for the same constructor method.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.