Wednesday, March 30, 2022

Constructor in Java

 

Constructor

  • A special method that matches the name of the class and has no return type
  • Constructors are executed when a new instance of the class is created (new Main()). This process is called instantiation, because it creates a new instance of the class.
  • The method name and the class name should be exactly same (note that Java is case sensitive)
  • Constructors can include parameters, like arrays, primitive types or generics. But cannot include var. The below constructor will not compile.

      class Main {
        public Main( var number ) {
    
        }
      }
    
  • There can be multiple constructors in a class, provided that the constructor parameters are distinct.
  • Declaring multiple constructors with different signatures is reffered to as constructor overloading.
  • Every class in Java will have a constructor. If you didn't code it Java will include the default no-argument constructor automatically during compilation process.
  • Private Constructor is a special constructor which is declared as private. Having private constructors prevents other classes from the class. It is generally used when the class has only static methods.

      class Main {
        private Main() {
    
        }
      }
    
  • Classes with a private constructor can be extended only by an inner class, because an inner class is the only one that can access a private constructor by calling super().

No comments:

Post a Comment