• 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

Need help on below code

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 !!!
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 .
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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().
 
reply
    Bookmark Topic Watch Topic
  • New Topic