aspose file tools*
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Default and super constructors" Watch "Default and super constructors" New topic
Author

Default and super constructors

Objsooj Ram
Greenhorn

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
Bartender

Joined: Apr 06, 2010
Posts: 4387
    
    8

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
Greenhorn

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="+this.name);
}

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
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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
Greenhorn

Joined: Oct 23, 2012
Posts: 9

thank you. i get the picture now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Default and super constructors