Constructors : Initializing an Class Object in Java Programming
A constructor in Java is a block of code similar to a method that's called when an instance of an object is created. Here are the key differences between a constructor and a method:
A constructor doesn't have a return type.
The name of the constructor must be the same as the name of the class.
Some Rules of Using Constructor :
- Constructor Initializes an Object.
- Constructor cannot be called like methods.
- Constructors are called automatically as soon as object gets created.
- Constructor don’t have any return Type. (even Void)
- Constructor name is same as that of “Class Name“.
- Constructor can accept parameter.
Default Constructor : How Constructor Works ?
class Box { //class name
int height; // variables
int width;
Box() // constructor same name as class name
{
height = 20; // initializing variables
width = 10;
}
}
class BoxExample {
public static void main(String args[]) {
Box b1 = new Box(); // creating object of Box class
System.out.println("Height of BOX : " + b1.height);
System.out.println("WIDTH of BOX : " + b1.width);
}
}
Output :
C:Zubair>java> BoxExample.java
C:Zubair>java BoxExample
Height of BOX : 20
WIDTH of BOX : 10
Example : Default constructor of a class
Explanation :
- new Operator will create an object.
- As soon as Object gets created it will call Constructor-
Box() //This is Constructor
{
height = 20;
width = 10;
}
- In the above Constructor Instance Variables of Object b1 gets their own values.
- Thus Constructor Initializes an Object as soon as after creation.
- It will print Values initialized by Constructor –
System.out.println("Length of Rectangle : " + b1.height);
System.out.println("Breadth of Rectangle : " + b1.width);
Parameterized Constructor:
An Example of a Box class with a constructor with parameters
//constructor
Box(double w, double h , double d){
width =w; height = h ; depth =d ;
}
// volume() is a function
double volume(){ return width * height * depth ;}
Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
ReplyDeletejava training in chennai | chennai's no.1 java training in chennai | best java institute in chennai
Good work sir, Thanks for the proper explanation about Polymorphism . I found one of the good resource related JAVA and OOPS concepts. It is providing in-depth knowledge on JAVA and OOPS. which I am sharing a link with you where you can get more clear on JAVA and OOPS. To know more Just have a look at this link
ReplyDeleteJava Tutorial
Class and object
Inheritance
Polymorphism
Abstraction
Encapsulation
..