World's most popular travel blog for travel bloggers.

Passing Object as Parameter to Method

, , No Comments

Passing Object as Parameter :

package com.pritesh.programs;

class Rectangle {
    int length;
    int width;

    Rectangle(int l, int b) {
        length = l;
        width = b;
    }

    void area(Rectangle r1) {
        int areaOfRectangle = r1.length * r1.width;
        System.out.println("Area of Rectangle : " 
                                + areaOfRectangle);
    }
}

class RectangleDemo {
    public static void main(String args[]) {
        Rectangle r1 = new Rectangle(10, 20);
        r1.area(r1);
    }
}

Output of the program :
Area of Rectangle : 200

Explanation :

  1. We can pass Object of any class as parameter to a method in java.
  2. We can access the instance variables of the object passed inside the called method.
area = r1.length * r1.width
  1. It is good practice to initialize instance variables of an object before passing object as parameter to method otherwise it will take default initial values.

Different Ways of Passing Object as Parameter :

Way 1 : By directly passing Object Name

void area(Rectangle r1) {
        int areaOfRectangle = r1.length * r1.width;
        System.out.println("Area of Rectangle : " 
                                + areaOfRectangle);
    }

class RectangleDemo {
    public static void main(String args[]) {
        Rectangle r1 = new Rectangle(10, 20);
        r1.area(r1);
    }

Way 2 : By passing Instance Variables one by one

package com.pritesh.programs;

class Rectangle {
    int length;
    int width;

    void area(int length, int width) {
        int areaOfRectangle = length * width;
        System.out.println("Area of Rectangle : "
                    + areaOfRectangle);
    }
}

class RectangleDemo {
    public static void main(String args[]) {
        Rectangle r1 = new Rectangle();
        Rectangle r2 = new Rectangle();

        r1.length = 20;
        r1.width = 10;

        r2.area(r1.length, r1.width);
    }
}
Actually this is not a way to pass the object to method. but this program will explain you how to pass instance variables of particular object to calling method.

Way 3 : We can pass only public data of object to the Method.

Suppose we made width variable of a class private then we cannot update value in a main method since it does not have permission to access it.
private int width;
after making width private –
class RectangleDemo {
    public static void main(String args[]) {
        Rectangle r1 = new Rectangle();
        Rectangle r2 = new Rectangle();

        r1.length = 20;
        r1.width = 10;

        r2.area(r1.length, r1.width);
    }
}

0 comments:

Post a Comment

Let us know your responses and feedback