• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor

 
c bhavana
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
}
}
 
Charlie Swanson
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic