-7

I will appreciate the help on this :

why we use below syntax for object creation :

A a = new A();

Why we are using default constructor? even if my class structure is like

class A{
  public static void main(String[] aregs)
  {
    A a = new A();
  }
}

I have not declare any instance variable then why i need default constructor ?

Why we have constructor name same as class name?

does constructor return any value or reference.

nobalG
  • 4,544
  • 3
  • 34
  • 72
  • 3
    This is pretty basic Java stuff - I'd recommend getting one of the introductory Java books of the web and reading - Eckel's Thinking in Java would be a good one. – BarrySW19 Nov 26 '14 at 09:29
  • probably so that you would be able to initiate the program flow without everything having to be in `static` context. – EpicPandaForce Nov 26 '14 at 09:29
  • See: [SO java-default-constructor](http://stackoverflow.com/questions/4488716/java-default-constructor) and [java constructor tutorial](https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html) - N.B. These were first two google hits. Actually, you could do worse than doing the whole [java tutorial](https://docs.oracle.com/javase/tutorial/java/index.html). – wmorrison365 Nov 26 '14 at 09:34
  • Thanks !!!! but i searched a lot on web as well as in books but nothing found satisfactory...if you have any relevant link in knowledge ..please share . – Chandan Chaudhary Nov 26 '14 at 09:42
  • @wmorrison365--Hi ,, link you mentioned is actually explaining what is default constructor.please look my question carefully..my concern point is why we need DC even if i am not having any variable. why we follow that syntex – Chandan Chaudhary Nov 26 '14 at 09:46

2 Answers2

0

I have not declare any instance variable then why i need default constructor ?

The constructor is needed for creating the object. Even if you didn't declare any fields in your class, you still need to call the constructor that will in turn(Automatically) call the constructors of the super class and then allocate an object on the heap, and return the reference to this allocated object.

Why we have constructor name same as class name?

That's simply the language specification.

does constructor return any value or reference

Yes, as I mentioned previously it returns a reference to the object created on the heap.

javaHunter
  • 1,097
  • 6
  • 9
0
  1. You need a default constructor so it can make an instance of the object. This is needed so it can get a memory address so java knows where the object data is stored
  2. It has the same name as the class so java knows which method(s) is/are the constructor
  3. The constructor doesn't return any value(s) and what it returns on the background is the memory addres (as stated in 1.)

This is all basic java stuff that comes with the language. If i were you i would look at this

Liam de Haas
  • 1,258
  • 3
  • 18
  • 39