Object As Parameters

12 0 0
                                        

class UsingObjectInParameter{

               private int instanceVariable1, instanceVariable2;

              private String name;


               UsingObjectInParameter(String title){

                                name = title;

               }

             UsingObjectInParameter(int arg1, int arg2){

                              instanceVariable1 = arg1; instanceVariable2 = arg2;

              }

             public int addingTwoNumbers(UsingObjectInParameter obj){

                          return obj.instanceVariable1 + obj.instanceVariable2;

             }

}

public class ObjectAsParameter{

             public static void main(String[] args){

                            UsingObjectInParameter obj1 = new UsingObjectInParameter(100, 200);

                           UsingObjectInParameter obj2 = new UsingObjectInParameter("Passing Object as reference");

                           System.out.println("The sum of the two numbers is " + obj2.addingTwoNumbers(obj1));

                  }

}

/*Output:The sum of the two numbers is 300*/

================================================================================

/*Meaning of the word or words*/

public int addingTwoNumbers(UsingObjectInParameter obj){} - we used an object as a parameter in the method named "addingTwoNumbers" whose name is "obj" from a class "UsingObjectInParameter". It has a return type of integer and is accessible as public.

UsingObjectInParameter(String title){} -  this is the first constructor with a parameter of a type String whose parameter variable name is "title".

UsingObjectInParameter(int arg1, int arg2){} - This is the second constructor in the same class whose parameter is both of type integer.

obj1, obj2 - these are the two objects that we created using those two constructors we create on class "UsingObjectInParameter".


 obj2.addingTwoNumbers(obj1) - we call the "addingtwoNumbers" method using the obj2 and we place the obj1 as an argument to be pass to that method.


You've reached the end of published parts.

⏰ Last updated: Jul 16, 2019 ⏰

Add this story to your Library to get notified about new parts!

Java codes i learned onlineWhere stories live. Discover now