• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

runtime and compile time error case confusion

 
sai panindra
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class A{

int aVar;

public A(int a){aVar=a;}

}

class B extends A{

int bVar;

public B(int b){

// super(10);

bVar=b;
}

public static void main(String[] args){

B b=new B(2);
}
}

In the above case, there 's a compilation error stating that the contructor A() is not present. But when I uncomment the line super(10).. the program compiles..

Please explain how this is a compilation error but not a runtime error. I presume that when a class extends another class, a super() call is made to the no arg constructor

unless another parameterized constructor of the super class is explicitly called. But I think this is known only during execution time
 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Sai,

Its similar to calling a method which is not defined in a Class and you would expect compiler to throw error ?

The compiler simply sees if there is constructor to call for it. In this case no arg constructor and it finds none ,as you have already have parametrized constructor.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sai:

Classes get an automatic no arg constructor only if you don't create any constructors. That's why your class will compile when you uncomment the line with super() in it. The reason why it's a compile-time error is that it has no way of compiling the subclass without calling the parent class.

John.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48940
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way of expressing it: This is one of those things the javac tool can recognise as a problem. So it prevents you from getting into trouble by not allowing the problem beyond the compiling stage.

You should be able to find out about constructors in any decent Java book.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic