0% found this document useful (0 votes)
64 views

Default Constructor

The document discusses default constructors and parameterized constructors in Java. A default constructor is automatically inserted by the compiler if no constructor is defined, while a parameterized constructor allows values to be passed when creating distinct object instances. Examples are provided showing how to define and call both default and parameterized constructors.

Uploaded by

manish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Default Constructor

The document discusses default constructors and parameterized constructors in Java. A default constructor is automatically inserted by the compiler if no constructor is defined, while a parameterized constructor allows values to be passed when creating distinct object instances. Examples are provided showing how to define and call both default and parameterized constructors.

Uploaded by

manish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Default constructor:

If you don’t implement any constructor in your class, the Java compiler


inserts default constructor into your code on your behalf. You will not
see the default constructor in your source code(the .java file) as it is
inserted during compilation and present in the bytecode(.class file).
Example:
1. //Java Program to create and call a default constructor  
2. class Bike1{  
3. //creating a default constructor  
4. Bike1(){System.out.println("Bike is created");}  
5. //main method  
6. public static void main(String args[]){  
7. //calling a default constructor  
8. Bike1 b=new Bike1();  
9. }  
10. }  
Output:
Bike is created

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a


parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to


distinct objects. However, you can provide the same values also.

Example of parameterized constructor


Example

1. //Java Program to demonstrate the use of the parameterized cons
tructor.  
2. class Student4{  
3.     int id;  
4.     String name;  
5.     //creating a parameterized constructor  
6.     Student4(int i,String n){  
7.     id = i;  
8.     name = n;  
9.     }  
10.     //method to display the values  
11.     void display(){System.out.println(id+" "+name);}  
12.    
13.     public static void main(String args[]){  
14.     //creating objects and passing values  
15.     Student4 s1 = new Student4(111,"Karan");  
16.     Student4 s2 = new Student4(222,"Aryan");  
17.     //calling method to display the values of object  
18.     s1.display();  
19.     s2.display();  
20.    }  

Output:

111 Karan
222 Aryan

You might also like