Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor

 
chintan ramavat
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello ranchers


why to WRITE SUPER() explicitly. what it does ? is that for initializing STATE of a class or any other reason ?


thank you ranchers
 
chintan ramavat
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what happens to the following code..

class A {

A (String name) {}
}

class B extends A {

B() {
super(); =======do we need to write super (String name)
}


Thanks rancher
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by chintan ramavat:
what happens to the following code... do we need to write super (String name)...

What happens when you compile this?
 
chintan ramavat
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
actually just want to know about SUPER. ? what it does ? if you give an example that would be great.


thank you
 
Mamatha Preetham
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chintan,

As Marc said, you should compile the code and see what does the compiler do....

super() is a keyword used to call the base class's constructor. The rule is that super() must be the first line in every constructor.

If you dont provide it, the compiler will automatically provide it with no arguments.

For the code which you had posted, the solution will be,
class A {

A (String name) {}
}

class B extends A {

B() {
super("Hi"); //yes, we do need to write super (String name), since the super class constructor takes String as argument
}
}

Cheers,
Mamatha
SCJP(1.4)
 
chintan ramavat
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks mamatha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic