Java Default Constructor
In this chapter you will learn:
- What is Java Default Constructor
- Syntax for Java Default Constructor
- Example - Java Default Constructor
- Example - auto-added default constructor
Description
A default constructor is a constructor with no parameters.
Syntax
Syntax for Java Default Constructor
class ClassName{/*from w ww .j a v a 2 s.co m*/
ClassName(){ // default constructor
...
}
}
Example
In the following code the constructor Rectangle()
is the default constructor.
class Rectangle {
double width;/* ww w .j av a 2 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);
}
}
If you don't declare a default constructor the Java compiler will add one for you. When you call the default constructor added by Java compiler the class member variables are initialized by default value. If you do provide a default constructor the Java compiler would not insert one for you.
The code above generates the following result.
Example 2
In the following code we removes the default constructor from class
Rectangle. When we compile the class Java compiler adds the default constructor for us
so we can still construct a Rectangle object by calling the default constructor.
But the value of width
and height
would be initialized to 0.0
.
class Rectangle {
double width;// w ww . j av a2 s. c o m
double height;
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);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- How to pass in value with parameters for constructors
- Syntax for Java Constructor Parameters
- Example - Java Constructor Parameters
- How to declare object parameters for constructors
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor ParametersJava 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