Constructors are special methods in Java that are automatically called when an object of a class is created to initialize all the class data members. If there are no explicitly defined constructors in the class, the compiler creates a default constructor automatically.
Default Constructor: A default constructor takes no arguments. Each object of the class is initialized with the default values that are specified in the default constructor. Therefore, it is not possible to initialize the different objects with different values.
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Example{ int roll_no; String name, classno, gender; Example(int roll, String n, String c) { roll_no = roll ; name = n; classno = c; } void display(){ System.out.println("My name is "+name+", I study in "+classno+" class and my roll number is "+roll_no); } public static void main(String arg[]){ Example sd1 = new Example(2, "James", "XIIth"); Example sd2 = new Example(25, "Alex", "IXth"); Example sd3 = new Example(1, "Michele", "XIth"); sd1.display(); sd2.display(); sd3.display(); } } |
Output: