• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Please explain the output

 
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

I couldn't understand the answer of this question I found from javablackbelt.

class A {
A() {
}
int x = 10;
B y = new B(); /* Do you think this will ever be executed*/
}

public class B extends A {
int x = 0;

public static void main(String[] args) {
B b = new B();
System.out.println(b.x);
}
}

The answer given is stack overflow and it is indeed the output when I run it on my system but I don't understand why? When we are creating Object of class B it will invoke default constrctor of class B and then A, so why the output is not 0 why there is a stack overflow.

Thanks in advance
Padma
 
Padma Asrani
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oops posted to a wrong place. Sorry
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi.

When you call B b = new B(), it invokes it's superclass constructor - A(). All member initializations are done automatically in the constructor's body (no matter where they appear), so y = new B() repeats this path again until StackOverflowError is thrown.

Alex

[ June 09, 2007: Message edited by: Aleksander Switalski ]
[ June 09, 2007: Message edited by: Aleksander Switalski ]
 
snakes are really good at eating slugs. And you wouldn't think it, but so are tiny ads:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic