• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help with error "constructor in class cannot be applied to given types"  RSS feed

 
poonam p patil
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello all,
Please explain me the error in d following progrm..

[Added code tags and formatting - please see UseCodeTags for details]

javac emptest.java
emptest.java:8: error: constructor person in class person cannot be applied to given types;
class emp extends person
required: String
found no arguments
reason: actual and formal argument lists differ in length
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you don't add a constructor to a class the compiler adds a no-arg constructor for you. So one is added to the emp class.

All constructors call (one way or another) a superclass constructor. If you don't add an explicit call to one then the compiler adds one for you.

So the code is equivalent to:
But that means it's trying to call a superclass constructor with no arguments. But there isn't one - the person class constructor requires a String.

What you've effectively done is say that all person objects must have a name provided. But then your emp objects - which are also person objects - don't provide a name. The compiler considers that an error.

(By the way, to follow standard Java conventions class names really should be capitalised: Person, Emp and EmpTest).
 
poonam p patil
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help Matthew.. it resolved my error.. but still i have 1 doubt.
class emp which extends person will invoke super() internally. Agreed !
But however constructor of class emp will be invoked if i create an object of class emp.
And in this case i m not creating object of emp in the main().
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It doesn't matter. The compiler knows you've made an error, so it's going to tell you. If you have code that does something that the compiler knows is invalid, then it will give an error. It's not going to waste time trying to work out if you ever actually call the code. This is a compiler error, not a runtime error.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is very difficult for a compiler to work out whether the code is ever called; it is obviously incorrect, so you get the error. It takes a long time for beginners to realise: the more errors you find at compile time, the better.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!