[go: up one dir, main page]

0% found this document useful (0 votes)
52 views9 pages

Lesson Set 5 Constructors & Passing Objects To Methods: Purpose

The document discusses constructors in Java and how to pass objects to methods. It defines constructors as special methods that initialize objects when they are created. It explains the two types of constructors - default (no argument) and parameterized constructors. It also discusses how objects are effectively passed by reference in Java when passed to methods, allowing the methods to modify the passed objects. An example is provided to demonstrate passing an object to a method and initializing one object using another object through a constructor.

Uploaded by

Nida Pari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views9 pages

Lesson Set 5 Constructors & Passing Objects To Methods: Purpose

The document discusses constructors in Java and how to pass objects to methods. It defines constructors as special methods that initialize objects when they are created. It explains the two types of constructors - default (no argument) and parameterized constructors. It also discusses how objects are effectively passed by reference in Java when passed to methods, allowing the methods to modify the passed objects. An example is provided to demonstrate passing an object to a method and initializing one object using another object through a constructor.

Uploaded by

Nida Pari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Lesson Set Constructors &

5 Passing Objects to Methods


Purpose 1. Clearly understand the purpose and benefits that OOP has
to offer.
2. Understand the concept of a class and objects.
3. Develop a basic class with fundamental data members.
4. Develop a basic class with a number of member functions.
5. Understand the concept of constructor.
6. Use the class objects and member functions to pass
objects to class member methods.

Procedure 1. Students should read the Pre-lab Reading Assignment


before coming to lab.
2. Students should complete the Pre-lab Writing Assignment
before coming to lab.
3. In the lab, students should complete Labs 5.1 through 5.4
in sequence.
4. Your instructor will give further instructions as to grading
and completion of the lab.
5. Students should complete the set of lab tasks before the
next lab and get them checked by their lab instructor.

Contents Pre-requisites Completion


Time

Pre-lab Reading Assignment - 20 min

Pre-lab Writing Assignment Pre-lab Reading 10 min

Lab 5

Lab 5.1 Reading Assignment 20 min

Lab 5.1 Lab 5.1 30 min


Defining Classes

Lab 5.2 Function parameter 30 min


Passing Objects and pass by values

Lab 5.3 Understanding of 40 min


Passing and copy objects Classes, function
calling

Constructor In Java, constructor is a block of codes similar to method. It is called when an


instance of object is created and memory is allocated for the object. It is a special
type of method which is used to initialize the object.
When constructor is Every time an object is created using new() keyword, atleast one constructor is
called called. It is called a default constructor.

Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.

There are basically two rules defined for the constructor.


Rules for Constructor
1. Constructor name must be same as its class name

2. Constructor must have no explicit return type

There are two types of constructors in java:


Types of Constructors

1. Default constructor (no-arg constructor)

2. Parameterized constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Default Constructor 1. <class_name>(){}

Syntax
1. class Bike1{
2. Bike1(){System.out.println("Bike is created");}
Example 3. public static void main(String args[]){
4. Bike1 b=new Bike1();
5. }
6. }

Purpose Default constructor is used to provide the default values to the object like 0, null
etc. depending on the type.

1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
}
Parametrized
Constructor A constructor which has a specific number of parameters is called parameterized
constructor. Parameterized constructor is used to provide different values to the
distinct objects.

Example In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

1. class Student4{
2.     int id;
3.     String name;
4.
5.     Student4(int i,String n){
6.     id = i;
7.     name = n;
8.     }
9.     void display(){System.out.println(id+" "+name);}
10.
11.     public static void main(String args[]){
12.     Student4 s1 = new Student4(111,"Karan");
13.     Student4 s2 = new Student4(222,"Aryan");
14.     s1.display();
15.     s2.display();
16.    }
Output }
111 Karan
222 Aryan
Passing Objects
Although Java is strictly pass by value, the precise effect differs between whether
a primitive type or a reference type is passed.
When we pass a primitive type to a method, it is passed by value. But when we
pass an object to a method, the situation changes dramatically, because objects
are passed by what is effectively call-by-reference. Java does this interesting
thing that’s sort of a hybrid between pass-by-value and pass-by-reference.
Basically, a parameter cannot be changed by the function, but the function can
ask the parameter to change itself via calling some method within it.
 While creating a variable of a class type, we only create a reference to an
object. Thus, when we pass this reference to a method, the parameter that
receives it will refer to the same object as that referred to by the argument.
 This effectively means that objects act as if they are passed to methods by
use of call-by-reference.
 Changes to the object inside the method do reflect in the object used as an
argument.
In Java we can pass objects to methods. For example, consider the following
Example program :
// Java program to demonstrate objects
// passing to methods.
class ObjectPassDemo
{
    int a, b;

    ObjectPassDemo(int i, int j)
    {
        a = i;
        b = j;
    }

    // return true if o is equal to the invoking


    // object notice an object is passed as an
    // argument to method
    boolean equalTo(ObjectPassDemo o)
    {
        return (o.a == a && o.b == b);
    }
}
// Driver class
public class Test
{
    public static void main(String args[])
    {
        ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
        ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
        ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

        System.out.println("ob1 == ob2: " +


ob1.equalTo(ob2));
        System.out.println("ob1 == ob3: " +
ob1.equalTo(ob3));
    }}
Defining a constructor that takes an object of its class as a
parameter:
One of the most common uses of object parameters involves constructors.
Frequently, in practice, there is need to construct a new object so that it is initially
the same as some existing object. To do this, either we can
use Object.clone() method or define a constructor that takes an object of its class
as a parameter. The second option is illustrated in below example:

// Java program to demonstrate one object to


// initialize another
class Box
{
    double width, height, depth;

    // Notice this constructor. It takes an


    // object of type Box. This constructor use
    // one object to initialize another
    Box(Box ob)
    {
        width = ob.width;
        height = ob.height;
        depth = ob.depth;
    }

    // constructor used when all dimensions


    // specified
    Box(double w, double h, double d)
    {
        width = w;
        height = h;
        depth = d;
    }

    // compute and return volume


    double volume()
    {
        return width * height * depth;
    }
}

// driver class
public class Test
{
    public static void main(String args[])
    {
        // creating a box with all dimensions specified
        Box mybox = new Box(10, 20, 15);

        //  creating a copy of mybox


        Box myclone = new Box(mybox);
        double vol;

        // get volume of mybox


        vol = mybox.volume();
        System.out.println("Volume of mybox is " + vol);

        // get volume of myclone


        vol = myclone.volume();
        System.out.println("Volume of myclone is " + vol);
    }
}

Pre lab writing assignment


Fill in the blanks 1. Primitive object type is passed by _________ to methods in java.
2. Every time an object is created using _______ keyword.
3. Atleast one constructor is called. It is called a ________ constructor.
4. A constructor which has a specific number of parameters is called
____________ constructor.
Lab 5

Lab 5.1 Copy the code, run and compile in JAVA IDE and paste the output in the space
given below:
// Java program to demonstrate objects
// passing to methods.
class ObjectPassDemo
{
    int a, b;

    ObjectPassDemo(int i, int j)
    {
        a = i;
        b = j;
    }

    // return true if o is equal to the invoking


    // object notice an object is passed as an
    // argument to method
    boolean equalTo(ObjectPassDemo o)
    {
        return (o.a == a && o.b == b);
    }
}
// Driver class
public class Test
{
    public static void main(String args[])
    {
        ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
        ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
        ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

        System.out.println("ob1 == ob2: " +


ob1.equalTo(ob2));
        System.out.println("ob1 == ob3: " +
ob1.equalTo(ob3));
    }}
Paste the output below:

Lab 5.2
Write a program that creates a class called CUBE. The data members of the
class are length, width height. Create constructor that will set the individual
values. In the end, create a function that will display all the data members.

Lab 5.3 Write a class called rectangle. Your task is to store the length and width of the
rectangle. Create constructor that will set the individual values taken as input
by the user. Finally write a function that will check if two objects are equal by
comparing the length and width, this function will take another rectangle as
parameter. Demonstrate the use of the object in the main function. Make sure
that the function names are meaningful and self-descriptive.

Lab 5.4 Write a program that creates a class called Student. Your class will have data
members namely name, cmsid, cgpa, array of marks. You will need to design
three functions as follows:

 Default Constructor.
 Parameterized Constructor.
 Function to copy data of one student to another.
 Function to display the student record.

Write a mainClass to demonstrate the usage of Student class. Also use array
of students and call respective methods of student class.

You might also like