• Register
1 vote
1.5k views

Problem:

Hello all,
Please explain to me the error in the following program.

​class test
{
  String name="name";
  public person(String nm){name=nm;}
}
 
class emp extends test
{
  String empid="0000";
}
 
public class emptest
{
  public static void main(String args[])
  {
    test p=new test("hello");
 
    System.out.println(p.test);
  }
}

The error I am getting is:

javac emptest.java
emptest.java:8: error: constructor test in class test cannot be applied to given types;
class emp extends test
required: String
found no arguments
reason: actual and formal argument lists differ in length

Thanks for the effort.

Best regards

15.3k points
edited by

Please log in or register to answer this question.

1 Answer

0 votes

Solution:

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:

class emp extends test  
{  
  String empid="0000";  
 
  emp() 
  {
    super();
  }
}

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 to 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.

94.3k points
edited by