Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Jargon mock exam

 
rubna
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a small doubt here about the correct answer
class Base
{
void test() {
System.out.println("Base.test()");
}

}

public class Child extends Base {

Child(int i) { test (); }

Child(float f) { this ((int)f); }

void test() {
System.out.println("Child.test()");
}

static public void main(String[] a) {
new Child(10.8f).test();
}
}
The correct answer is Child.test() Child.test().
I compiled it too & got the same answer.
But when we call the constructor Child(float f),does'nt it try to call the default base class constructor?I thought that it would give the compiler error by saying that there's no match for base class constructor super()?Can anybody please verify this for me?
Thanks,
rubna
 
Herbert Maosa
Ranch Hand
Posts: 289
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hie Rubna,
Your question :
-------------------------------
I thought that it would give the compiler error by saying that there's no match for base class constructor super()?Can anybody please verify this for me?
-------------------------------------
If you do not supply a constructor for your class, An implicit constructor is provided for you, called the default constructor.The default constructor takes no arguments and all it does is to call super().So in your base class you did not provide a constructor and as such you get this default construtor.So you dont get that error because it is this default constructor that answers super() when you create new Child(10.8).
Regards,
Herbert.
 
rubna
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Herbert Maosa:
Hie Rubna,
Your question :

Thanks a lot Herbert.U made it clear for me.
 
sgwbutcher
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is true as far as it goes but don't forget that if a parameterized constructor exists in the base class, you have to provide the non-parameter constructor manually, the compiler won't give you the free default constructor anymore.
If Base was defined as:
class Base {
Base( int i ) {
int x = i; // something stupid
}
// now needs no-parameter constructor for subclassing
void test() {
System.out.println( "Base.test()" );
}
}
Then you *would* have gotten a compiler error.

Steve Butcher
exceptionraised@aol.com
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic