Skip to main content

Posts

Showing posts with the label Constructors

Constructors

Constructors | Java: Constructor is called when the object is created. It is also a method with the same name of class. Syntax:                        class class_name {                                                 // statements.                                                 class_name(par1,par2,...,parn) // constructor                                                 {                                                              // statements                                                  }                                      } Here is the Code: import java.io.*; class Main { public static void main (String[] args) { A a = new A(1); A b = new A(); System.out.println(a.x); System.out.println(b.x); } } class A {     int x;     A(int x)     {         this.x = x;     }     A()     {         this.x = 2;     } } Output: 1 2 Here is the Video: