Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Default and super constructors

 
Objsooj Ram
Greenhorn
Posts: 9
Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 6109
6
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you. i get the picture now.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic