*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Need help on below code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Need help on below code" Watch "Need help on below code" New topic
Author

Need help on below code

Dinesh Tahiliani
Ranch Hand

Joined: Aug 06, 2007
Posts: 486
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.


Thanks<br />Dinesh
Abhishek Mantri
Greenhorn

Joined: Sep 06, 2007
Posts: 25
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

Joined: Dec 09, 2007
Posts: 21
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

Joined: Jul 10, 2007
Posts: 7
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().
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Need help on below code
 
Similar Threads
A question on GC and String literals.
Initialization
Reference to objects
doubt
Example of wait and notify