Developer community
0 votes
16k views
asked by Guru (24.6k points) 30 54 83 | 16k views

1 Answer

0 votes
A constructor initializes an object during object creation when using new operator.
 
Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.
Syntax
 
It has the same name as the class. Constructors have no return type, not even void.
 
 
class ClassName{
 
   ClassName(parameter list){ // constructor
    ...
   }
}
 
Example
 
In the following code the Rectangle class in the following uses a constructor to set the dimensions:
 
 
class Rectangle {
  double width;
  double height;
 
  Rectangle() {
    width = 10;
    height = 10;
  }
 
  double area() {
    return width * height;
  }
}
 
public class Main {
  public static void main(String args[]) {
    Rectangle mybox1 = new Rectangle();
    double area;
    area = mybox1.area();
    System.out.println("Area is " + area);
 
  }
}
 
answered by Sr Member (5k points) 7 9 12

Related questions

0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 25 31 | 100 views
0 votes
1 answer
asked by sara Guru (24.6k points) 30 54 83 | 25 views
0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 25 31 | 76 views
0 votes
1 answer
asked by rock Expert (15k points) 15 23 31 | 25 views
0 votes
1 answer
asked by john Guru (27.1k points) 33 51 102 | 34 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users