Constructor Declarations in Java Programming
Previous | Home | Next |
A constructor method is a method that creates an object.
To create the object, it uses the class as a sort of blueprint for what member variables the object has, what instance methods, and so on.
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations
look like method declarations—except that they use the name of the class and have no return type.
If you declare a class with no constructors, the compiler will automatically create a default constructor for the class.
A default constructor takes no parameters (it's a no-arg constructor) and has an empty body. Because the compiler will
automatically generate a default constructor if you don't declare any constructors explicitly, all classes are guaranteed
to have at least one constructor
class Tea
{
// Constructor looks like a method declaration
// minus the return type
public Tea() {
// Body of constructor
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call.
Constructor arguments provide you with a way to provide parameters for the initialization of an object.
The following example consists two constructor one default and one parametrized constructor
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
public class Figure {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Figure1() {
length = 12;
breadth = 10;
height = 15;
}
Figure1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Figure1 FigureObj1, FigureObj2;
FigureObj1 = new Figure1();
FigureObj2 = new Figure1(10, 20, 30);
System.out.println("Volume of Figure1 is : " + FigureObj1.getVolume());
System.out.println("Volume of Figure1 is : " + FigureObj2.getVolume());
}
}
Previous | Home | Next |