Posts Tagged passing objects

Java Tutorial 8 – Passing objects as argument

first create 1 new class (i have named it Class3 for make it simple to understand)

and add the code to all thre classes as follows

(after copy and pasting press Alt+Shift+f  and it will formate everything…)

Class1:

public class Class1 {

public static void main(String[] args) {

//created two objects

Class3 c3ob = new Class3();
Class2 c2ob = new Class2();

//passing object of Class3 to method of Class2

c2ob.basket(c3ob);

}

}

Class2:

public class Class2 {
int i;
public void basket(Class3 receivedfriut){
for(i=0;i<3;i++)
System.out.println(receivedfriut.fruit[i]);
}

}

Class3:

public class Class3 {
String fruit[] ={ “apple”, “banana”, “grapes” };

}

  1. we created two objects of class2 and class3
  2. we passed and object of class3 as arguiment of method of class 2
  3. we defined basket method in class2 which takes object of Class3 and save it in receivedfruit
  4. we used receivedfruit object and printed the String array.

This is useful when you are dealing with lots of int,doubles and etc. You can make a different class for it and use it in other Classes and methods by passing objects.

inough bla bla bla, Doubts are invited,

Have a nice day, Peace.

, , , ,

1 Comment

Design a site like this with WordPress.com
Get started