DEV Community

MANOJ K
MANOJ K

Posted on

Java Constructors :

  • In Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automatically when we use the "new" keyword to create an object.

Characteristics of Constructors:

  • Same Name as the Class: A constructor has the same name as the class in which it is defined.

  • No Return Type: Constructors do not have any return type, not even void. The main purpose of a constructor is to initialize the object, not to return a value.

class Human {
String name;
int age;
double height;
double weight;

Human(String name,int age,double height,double weight){

   this.name = name;
   this.age = age;
   this.height= height;
   this.weight= weight;

   }

void calculateBMI(){
     double BMI = weight/(height*height);
          System.out.println("manoj BMI " +BMI);
     }

public class Constructor{

  public static void main (String [] args){

  Human manoj = new Human("manoj",21,1.69,58.7);
  manoj.calculateBMI();

  }
}


output:
manoj BMI 20.552501663107037

Enter fullscreen mode Exit fullscreen mode

Reference

https://www.geeksforgeeks.org/java/constructors-in-java/

Top comments (0)