The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
December 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

default constructors

Posted by Jody Brown on December 09, 2000 at 5:30 PM

Harpreet,

Constructors are called whenever a new object is created. If, when you are writing a class, you dont define a constructor, a default one is implied. For example:

Class MyClass() {
// this is my class
}

is interpreted as:

Class MyClass() {
MyClass() {
// this is the implied constructor
}
// this is my class
}

This constructor will be called when the following code is executed:

MyClass testClass = new MyClass();

However, if you declare a constructor that takes a parameter, the default constructor is no longer implied. For example:

Class MyClass() {
MyClass(int i) {
// constructor to do something with i
}
// this is my class
}

so the following code is now illegal:

MyClass testClass = new MyClass();

An int HAS to be passed as a parameter, because MyClass's only constructor requires one.

This is complicated when you use inheritance. In your example, in b's constructor, an implicit call is made to a's default constructor using super();
This is so a subclass can use its parent class's constructor to initalise inherited members.

You cant see this call to super() in your code, but it is there. Because b is attempting to call a's default constructor, which doesnt exist, it results in an error.

What you need to do is add a default constructor to class a, so class a reads along the lines of:

class a
{
a()
{}
a(int i)
{
System.out.println("In Class A");
}
}

Hope this is clear enough. I found this tricky to grasp when I first started using Java.

Good luck with Java,

Regards,

Jody




Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us