July 22nd, 1999, 07:29 PM
Suppose I create a constructor for my base class A. Then another class B (sans constructor) inherits from that class. If I say
B test = new B(12,3); // assuming A had a constructor that takes 2 ints
Will Java call the constructor from the base class??
varbsjava
July 22nd, 1999, 11:29 PM
Normally when u create an object of a class which extends from a Other class, first the consrtructor of the super class is called and then its constructor is called. But which constructor is called depends upon what u have given in the constructor of the sub class. For example,
public class A{
public A(){
}
public A(int i1,int i2){
System.out.println("I am in Constructor A");
}
}
public class B extends A{
public B(int i1,int i2){
super(i1,i2);
System.out.println("I am in Constructor B");
}
}
In the above case u have explicity called the super class constructor in the constructor of B. So first the Super class constructor will be get called. If u won't mention super(int,int), then it will call the default constructor of the Super class i.e. the constructor with no arguments. If there is no such constructor in the super class then u will get compilation error saying that "No constructor matching A() found in class A". U have to take care this in the super class. U have to write a default construtor in class A.
Also if u r making a call to the super class constructor, it has to be the first call in the constructor of sub class.
I hope this will answer your question.
regards,
arun...