How to use constructor in java bluej




Hello and thanks for taking the time to view this blog post,  what I'm going to show you within this video, will be how to use a constructor in BlueJ. A constructor is used when you want to assign a value to the object that we will be created on the main method later on, but first, we need to create a class of the object then define the width and the height before we pass it to the constructor, we do this so we can pass the exact value to the main field of our new object created.

Example:


public class Rectangle {
private int width;
private int height;

  public Rectangle(int width, int height){
    this.width = width;
    this.height = height;

}
public static void main(String [] args){
  Rectangle rect = new Rectangle(200,100);
System.out.println(rect.width);
System.out.println(rect.height);
}

}





Post a Comment

0 Comments