• Post Reply Bookmark Topic Watch Topic
  • New Topic

???strange???  RSS feed

 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Super
{
static int x = 5;
static void main(String args[])
{
System.out.println("This is Super class : "+x);
}
}
class Sub extends Super
{
static void main(String args[])
{
System.out.println("This is Sub class : "+x);
}
}
The code azaman posted last day,when I test,I got the answer:
java Super
This is Super class : 5
java Sub
This is Sub class : 5
But David said it should be 0 in Sub class,not 5...
??? what's the problem ??
---------
Liao
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not see any reason that sub class should get 0.
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
here x in not in Sub class. Its is declared and initialized in Super where is 5. Hence the output.
 
Ranch Hand
Posts: 1157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The answer in this case, will always be 5.The variable x which is a static variable gets initialized before creation of any object of either class.It will get initialized even though the object is not created using the new operator.
Hope this helps,
Sandeep
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!