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

Need help on below code

 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class X
{
X(String s)
{
System.out.println("hi");
}
public static void main(String[] args)
{
new X(null);
new Inherit("Dinesh",21);

}
}
class Inherit extends X
{
int i;

Inherit(String p,int x )
{
super(p);
i=x;
System.out.println("hello");
}



}

o/p
hi, hi, hello.
Why its printing two times hi.
 
Abhishek Mantri
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi dinesh,
I think the code is working fine !!!

You get first "hi" since you have invoked X's constructor...agreed?

You get second "hi" since you have again invoked X's constructor...agreed?
check that irrespective of what String you send to X's constructor, it will only print "hi"

I think that solves your problem,rest you know!
good luck !!!
 
npk chowdary
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am expecting that you are thinking about this code as why it is working even while passing null to string object.
here you are passing null means you are indirectly assigning string object to null.It leads to no problem in the constructor because you are not using String s for manipulation anywhere in your constructor.
I think it will clears .
 
yong huang
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I also learnt from this topic that below sentence A should be replaced with B.

A. The first line in a constructor Must be a call to super() or a call to this().

B. The first line in a constructor Must be a call to super() , or its overloaded version, or a call to this().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic