0
 class A {
    int a, b;

    A(int i, int j) {
        a = i;
        b = j;
    }
}

class B extends A {
    int c, d;

    B(int i, int j) {
        c = i;
        d = j;
    }
}

public class HelloWorld {

    public static void main(String[] args) {
        A aa = new A(5, 6);
        B bb = new B(3, 4);
        System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);

    }
}

it gives error as

HelloWorld.java:9: error: constructor A in class A cannot be applied to given types;                                                                                 
{                                                                                                                                                                    
^                                                                                                                                                                    
  required: int,int                                                                                                                                                  
  found: no arguments                                                                                                                                                
  reason: actual and formal argument lists differ in length                                                                                                          
1 error 
Jens
  • 67,715
  • 15
  • 98
  • 113
Ms.Rey
  • 21
  • 2

2 Answers2

0

As you class B extends class A, you somewhere have to call the constructor of the class you are extending.


As your class A does not have a constructor with no arguments, you need to explicitly call the super constructor (the constructor from class A) as the first statement inside the constructor of your class B:

B(int i, int j) {
  super(i, j);
  // Your code
}

If you would have a no-args constructor in A, you would not need to do this, as the no-args constructor is implicitly called if no constructor call is specified:

B(int i, int j) {
  // Your code
}

Is actually doing:

B() {
  super();
  // Your code
}

And as you do not have A() as a constructor, you get the error.

JDC
  • 4,247
  • 5
  • 31
  • 74
0

Check this one... JVM always looking for no argument constructor.

class A {
    int a, b;

    A(int i, int j) {
        a = i;
        b = j;
    }

    public A() {
        // TODO Auto-generated constructor stub
    }
}

class B extends A {
    int c, d;

    B(int i, int j) {
        c = i;
        d = j;
    }
}

public class pivot {

    public static void main(String[] args) {
        A aa = new A(5, 6);
        B bb = new B(3, 4);
        System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);

    }
}