简体   繁体   中英

Why constructor is not invoked after creating Object of the class?

public class A {                                    
    void A()  {
        System.out.println("Class A"); 
    } 
    public static void main(String[] args)  { 
        new A(); 
    } 
}

After running this program output is nothing means after new A(); void A(){} is not invoked.

void A(){} isn't a constructor ?

void A() is a regular method, not a constructor.

A() (without a return type) is a constructor.

A() 
{
    System.out.println("Class A"); 
} 

You didn't write constructor in your class you wrote an ordinary method yet the compiler provides you a default constructor (constructor with no parameters) read more

To create constructor:-

  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

ex:-

A() 
{
  System.out.println("Class A");    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM