Search code examples
javaclassconstructorcoupling

Details about implicit constructor in java with example


I want a clarification for this statement related to implicit constructor in Java. I read this statement in an article but I need more details about it and an example to understand it.

The statement is: An implicit constructor call is made when a variable of type B is defined and instantiated in class A, for example, B b = new B().


Solution

  • Its basically saying that any class that is instantiated has an implicit constructor:

    public class B {
    
        //constructor       
        public B() {
            //implicity constructor
        }
    
    }
    
    public class A {
    
        //constructor       
        public A() {
             Bb = new B(); //calls the constructor inside B during setup even if the constructor method does not exist within B an implicit constructor is made
        }
    
    }
    

    The default constructor is the no-argument constructor automatically generated unless you define another constructor. It initialises any uninitialised fields to their default values. link

    When B is instantiated from A this constructor is called during its creation basically. For more specific details you should really ask in a different exchange than stack-overflow maybe try the programmers section.