1

I was practising some of the inheritance concept which i have learned from my book although i haven't completely studied inheritance yet but i thought to just write a simple program based on inheritance here is it

public class InheritanceInJava
{
    public static void main(String args[])
    {
       SupperClass_A supperObj_A = new SupperClass_A(20,30,10);
       SubClass_A subObj_A = new SubClass_A(10,20,30);
       System.out.println(subObj_A.Add());
       System.out.println(subObj_A.Multiply());
    }
}

class SupperClass_A
{
   int num1 ; int num2 ; int num3 ;
   SupperClass_A(int a, int b, int c)
   {
      num1 = a ; num2 = b ; num3 = c;
   }
  public int Multiply()
  {
     return num1 * num2 * num3;
  }
}

class SubClass_A extends SupperClass_A
{
  SubClass_A(int a, int b, int c)
  {
      num1 = a ; num2 = b ; num3 = c;
  }
  public int Add()
  {
      return num1 + num2 + num3;
  }
}

but it shows one error which is :

constructor SupperClass_A in class SupperClass_A cannot be applied to given types; { ^ required: int,int,int found: no arguments reason: actual and formal argument lists differ in length

Can anyone help me understand why this program is not working and whats the cause for this error ?

3
  • since you declared a parameterized constructor in your SuperClass_A you have to call it from the Constructor in your SubClass. Commented Oct 27, 2016 at 12:51
  • 1
    (Correcting SupperClass to SuperClass) -- A SuperClass_A constructor has to be called when you make a SubClass_A instance, because every SubClass_A instance is also a SuperClass_A instance. Your SubClass_A does not specify what SuperClass_A constructor should be called (using super(a,b,c)), so the compiler assumes you want to call the no-arguments constructor. But there isn't a no-arguments constructor, so the compile fails. Commented Oct 27, 2016 at 12:51
  • Possible duplicate of Java inheritance - constructors Commented Oct 27, 2016 at 12:52

1 Answer 1

4

The issue is that your SubClass_A constructor attempts to implicitly call a parameter-less constructor of SupperClass_A, which doesn't exist. A parameter-less constructor is generated automatically by the compiler only for classes that don't have any explicitly defined constructors.

You can fix it by calling the super class constructor explicitly :

class SubClass_A extends SupperClass_A
{
  SubClass_A(int a, int b, int c)
  {
      super(a,b,c);
  }
  public int Add()
  {
      return num1 + num2 + num3;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.