• Register
1 vote
38 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

12 7 7
15,250 points

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.

13 9 6
94,240 points

Related questions

0 votes
1 answer 57 views
57 views
Problem : I have the below two classes public class A {     A() {         System.out.println("A");     } } class B extends A {     B() {         System.out.println("B");     } } And after that running 1 A c = new B(); or 2 B c = new B( ... glance, in either of the scenario, I would assume that only a B constructor would be called and so the only output would be B But this is completely wrong.
asked Jan 23 jwilliam 3.9k points
0 votes
1 answer 40 views
40 views
Problem : I have following two classes: JDialog and JFrame (see signature below). I want them to have few extra methods, but I also want them both to extend my code, without rewriting the code Is it possible to do that? java.awt.Window java.awt.Dialog javax.swing. ... the identical way. So I will not want to write the code twice. I want only one class to utilize the code of the other class.
asked Dec 7, 2019 alecxe 7.5k points
0 votes
1 answer 10 views
0 votes
1 answer 629 views
629 views
Problem : Getting below eclipse error the class file viewer cannot handle the given input ('org.eclipse.ui.ide.filestoreeditorinput').
asked Nov 12, 2019 peterlaw 6.9k points