GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructor" Watch "constructor" New topic
Author

constructor

c bhavana
Greenhorn

Joined: Feb 04, 2001
Posts: 5
hi
suppose i have a base class called a without any constructor
and a derived class b with one-arg constructor .I get an error saying constructor mismatch.in case i provide an empty constructor in the base class the program compiles fine.
can somebody explain the reason for this
thanks
rani bedi
Ranch Hand

Joined: Feb 06, 2001
Posts: 358
Well the code i wrote with your description works fine.
class demo
{
}
class demo1 extends demo
{
demo1(int i)
{}
public void method2()
{
System.out.println("inside the demo1");
}
}
public class testclass
{
public static void main(String s[])
{
demo1 dd = new demo1(5);
dd.method2();
System.out.println("CORRECT");
}
}

Cheers,<br />Rani<br />SCJP, SCWCD, SCBCD
Charlie Swanson
Ranch Hand

Joined: Jan 29, 2001
Posts: 213
The super class constructor is called for the child constructor if the first statement in the constructor is not "this" or "super".
for example:
1. class parent { Parent() {System.out.println("In Parent"); }
2. }
3. class child extends parent {
4. child() {
5 System.out.println("Child");
6. }
When the child constructor executes the following will happen.
4. execute child()
5. Call the constructor Parent()
6. execute line 5.
Keep in mind that the compiler will create this no arguement constructor for you if no other constructors in that class have been created. If a constructor is created, the no arguement constructor will not be created automatically.
Hope that points you in the right direction.
niraj singh
Ranch Hand

Joined: Feb 07, 2001
Posts: 36
Hi bhavana,
It would be better, if you posted your code for us to troubleshoot, as it does not appear, what you are saying could happen.
Java always calls the parent class constructor automatically whenever the child class constructor is executed. If the parent class does not have a explicitly defined constructor, a default constructor is created by Java.
If there is one or more (overloaded) explicitly defined constructor ( it may be a no-parameter constructor or a parameterized constructor), you will have to explicitly call the parent class constructor using -
super();
or
super( arg1, .....);
Naresh Nihalani
Greenhorn

Joined: Feb 08, 2001
Posts: 6
I think Niraj is right.
Java always calls the parent class constructor automatically whenever the child class constructor is executed. If the parent class does not have a explicitly defined constructor, a default constructor is created by Java.
 
GeeCON Prague 2014
 
subject: constructor