This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Default and super constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Default and super constructors" Watch "Default and super constructors" New topic

Default and super constructors

Objsooj Ram

Joined: Oct 23, 2012
Posts: 9

[Added code tags, see UseCodeTags for details]

Hey All,
When I try to call a parent class constructor in a subclass that I defined, it tries to look for a non-arg constructor.
I know that in a constructor, super() is called by default. So in that case, super() of class A i.e Object does have this default constructor, so why is it trying to call B's constructor?

// Error: constructor A in class A cannot be applied to given types;
public B(){}
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error

Matthew Brown

Joined: Apr 06, 2010
Posts: 4344

All constructors result in a call to a superclass constructor at some point. If you don't make an explicit call yourself, the compiler inserts one for you. But it will always insert a call to a no-arg constructor (if it used arguments, what would it pass?).

So the compiler is treating your code as if it was:
So it's trying to call the no-arg contructor in A, and that doesn't exist. That's a compiler error. It doesn't matter that your main method never tries to create a B - the compiler won't let you refer to constructors, methods or variables that don't exist.
Objsooj Ram

Joined: Oct 23, 2012
Posts: 9

class A{
String name;

public A(String s){
name = s;
System.out.println("in A="+name);

public class B extends A{

public B(){
super("from super"); //line 1
System.out.println("in B=";

public static void main(String... arg){
A aa = new A("from main");


hi there, I modified the code to understand the flow as per your expln. I added line1 and no error and the output is

in A=from main

Now, i am curious what did the line1 actually do?

Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

Objsooj Ram wrote:
super("from super"); //line 1
Now, i am curious what did the line1 actually do?

It says, "Invoke the superclass constructor that takes a single String argument, and pass it a reference to the String 'from super'".
Objsooj Ram

Joined: Oct 23, 2012
Posts: 9

thank you. i get the picture now.
I agree. Here's the link:
subject: Default and super constructors
Similar Threads
Default Constructor in Sub/Super Class
default constructor?????
Constructor problem
Question from Dan's test