Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

What for do we need constructor?

843789Feb 4 2010 — edited Feb 4 2010
Hi I just wonder, if I can have construction like this:
public class MyClass
{
private int a = 5;
private AnotherClass another = new AnotherClass();
public MyClass()
{
//absolutely nothing to do in here
}
}
which lets me initialize variables directly in class definition what for do we need constructor? I always thought that we should initialize object via constructor but as java lets us do it without constructor what is the point of having one? Except of course to provide a way to tell compiler that we want another object of this class by saying:
MyClass myClass = new MyClass();
Thanks for any answers.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 4 2010
Added on Feb 4 2010
6 comments
135 views