• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

runtime and compile time error case confusion

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic