Java Class Constructors
In this chapter you will learn:
Description
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{// ww w.ja v a 2 s . c o m
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;/* w ww . j a va2 s . c o m*/
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);
}
}
When this program is run, it generates the following results:
Next chapter...
What you will learn in the next chapter:
- What is Java Default Constructor
- Syntax for Java Default Constructor
- Example - Java Default Constructor
- Example - auto-added default constructor
Java Class
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Class Constructors
Java Default ConstructorJava Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files