Methods in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

In this tutorial, we will discuss different ways of method definition with sample codes. This tutorial covers how objects are passed in a method and an object is returned by a method.


Passing Object as Parameters


An object of a class can be passed in a method as an argument. More than one objects of one class or different classes can also be passed in the method as parameters (according to the requirements). In the following example we will show how to pass an object as parameter.

Code ComplexNum.java
public class ComplexNum { float x; float y; public ComplexNum(float x, float y) { this.x = x; this.y = y; } public boolean isEqual(ComplexNum obj) { if (obj.x == x && obj.y == y) return true; return false; } }

Source code of Test.java
public class Test { public static void main(String[] args) { ComplexNum c1 = new ComplexNum(5, 7); ComplexNum c2 = new ComplexNum(5, 7); System.out.println(c1.isEqual(c2)); } }


Returning an Object


A method can also return an object. In the following example, we are showing that add method receives two objects of ComplexNum class and it returns an object of ComplexNum class.

Source code of ComplexNum.java
public class ComplexNum { float x; float y; public ComplexNum(float x, float y) { this.x = x; this.y = y; } public ComplexNum add(ComplexNum obj1, ComplexNum obj2) { return new ComplexNum(obj1.x + obj2.x, obj1.y + obj2.y); } }

Source code of Test.java
public class Test { public static void main(String[] args) { ComplexNum c1 = new ComplexNum(5, 7); ComplexNum c2 = new ComplexNum(5, 7); ComplexNum c = c1.add(c1, c2); System.out.println(c.x + " " + c.y); } }


Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.