How to use constructor in java programming tutorial

Moving on to this lesson, we will learn about how to define and use the constructor for object initialization. check out the program below. it defines a class Rectangle with a constructor that takes a width parameter.

public class Main(){
public static void main(String [] args){
Rectangle rect = new Rectangle(100,200);
Rectangle rect2 = new Rectangle(20,40);
Rectangle rect3 = new Rectangle(100,100)
System.out.println(rect3.width);
System.out.println(rect3.height);
System.out.println(rect.width);
System.out.println(rect.height);
System.out.println(rect2.width);
System.out.println(rect2.height);
}
}
class Rectangle{
int width;
int height;
// A constructor
Rectangle(int width, int height){
this.width = width;
this.height = height;
}
//new constructor added
Rectangle(){
this.width =100;
this.height= 100;
}
}

in the main method, we create a new Rectangle object and pass the value 100 to the constructor. Then finally we print the width field of the new Rectangle object. Guess what the program prints, The width field of our newly created Rectangle object is 100, now we add parameter "height" to the constructor separated by a comma and pass a value of 200, then we initialize the height field with the parameter value in the constructor in the main method we print "rect.height" as well. using the constructor it is now easy to create objects. you should see the print result of width as 100 and height is 200. for your activity: create a second Rectangle Object with width "20" and "40", Assign it to variable "rect2" and print the width and height fields. A class can also have more than one constructor. Add another constructor which takes no parameters, in the main method we've created a new Rectangle Object with the new constructor we assign it to variable "rect3" and print width and height fields.

Post a Comment

0 Comments