So far we've only been using simple types like int, double etc as parameters in methods and constructors.But we can pass objects to methods & constructors and also use objects as parameters in the methods & constructors.
The following example statements will show how to pass objects to methods & constructors :
Example: Passing Object 'box2' to Box( ) constructor in Box Class
Box box1 = new Box(box2);
- box1 and box2 are objects of Box class
- Here in this example we're passing the box2 object to Box( Box object) constructor in Box class
boolean x = box1.equal(box2);
- box1 and box2 are objects of Box class
- x is the boolean type variable which can store either true or false
- equal( ) is a method of Box class which has the object parameter i.e. public boolean equal(Box object)
1. Launch Eclipse IDE, Create a new Project 'Project 004' , Create a class called 'Box' and declare 'width', 'height' and 'depth' as instance variables as shown below:
Download this Project:
Click here to download the project containing 'Box' and 'PassingObjects' classes used in this post (You can download the project and import into Eclipse IDE on your machine)
Lets implement 'passing the object to a method' on Eclipse IDE
Before starting it, I want to tell you that the method that receives object as parameter in this project is going to compare two objects.
1. Launch Eclipse IDE, Create a new Java Project 'Sixth Project', Create a package 'sixth_package', Create a class called 'Test' under 'sixth_package' package of 'Sixth Project' project as shown below:
7. Compare two objects and print the result returned by the equals( ) method as shown below:
9. Observe that the output is displayed in console as shown below:
Click here to download the project containing 'Test' and 'PassObjects' classes used in this post (You can download this project and import into Eclipse IDE on your machine)
Please comment below to feedback or ask questions.
Two ways of argument passing topic is explained in the next post.
2 comments:
When i run this code i get both False, why ?
You may be doing some mistake. Please try again fresh and start again.
Post a Comment