• 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

superclass no-arg constructor... mock question

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

i dont understand why this code compiles properly?

class A
{
public A() {} // A1
public A(String s) { this(); System.out.println("A :"+s); } // A2
}
class B extends A
{
public int B(String s) { System.out.println("B :"+s); return 0; } // B1
}
public class C extends B
{
private C(){ super(); } // C1
public C(String s){ this(); System.out.println("C :"+s); } // C2
public C(int i){} // C3

public static void main(String[] args) {
C c = new C();
}
}


Since there is no no-arg constuctor in B ( we need to type it in because we have defined ome other constructor) , wont calling the super() from line C1 cause a compiler error?? what am i missing here?
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Radha,

I guess, you must have got confused with the name of the method in B. If you see, there is no construtor defined in class B and hence compiler provides a default constructor. In fact at the very first glance even I thought like you and even executed it keep a println statement in no arg construtor A . This is one of the serious traps in SCJP exam, which we should be care enough.
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public int B(String s)

This is not a constructor. This is a method, having the same name as constructor. Because constructors have no return types.
 
Radha Kamesh
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
yes... how careless of me...

Thanks friends...
 
I guess everyone has an angle. Fine, what do you want? Just know that you cannot have this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic