Developer community
0 votes
15.1k views
asked by Guru (24.6k points) 31 57 92 | 15.1k views

1 Answer

0 votes
The constructors can also have parameters. Usually the parameters are used to set the initial states of the object.

Syntax

Syntax for Java Constructor Parameters

class ClassName{

   ClassName(parameterType variable,parameterType2 variable2,...){ // constructor
    ...
   }
}

Example

In the the following demo code Rectangle class uses the parameters, w for width and h for height, from the constructors to initialize its width and height.
 
class Rectangle {
  double width;
  double height;

  Rectangle(double w, double h) {
    width = w;
    height = h;
  }

  double area() {
    return width * height;
  }
}

public class Main {
  public static void main(String args[]) {
    Rectangle mybox1 = new Rectangle(10, 20);
    double area;
    area = mybox1.area();
    System.out.println("Area is " + area);
  }
}
answered by Guru (24.6k points) 31 57 92

Related questions

0 votes
1 answer
asked by kelly johnes Advisor (6.3k points) 6 22 35 | 1.3k views
0 votes
1 answer
asked by taye Sr Member (5k points) 7 10 12 | 15.9k views
0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 26 32 | 97 views
0 votes
1 answer
asked by rock Expert (15k points) 15 23 32 | 32 views
0 votes
1 answer
asked by taye Sr Member (5k points) 7 10 12 | 20 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,754 questions
4,046 answers
117 comments
10,709 users