• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

runtime and compile time error case confusion  RSS feed

 
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
 
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.
 
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.
 
Marshal
Posts: 60130
188
  • 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
Boost this thread!