简体   繁体   English

了解Java中的继承

[英]Understanding Inheritance in java

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; SupperClass_A类中的构造函数SupperClass_A不能应用于给定类型; { ^ required: int,int,int found: no arguments reason: actual and formal argument lists differ in length {^必填:int,int,int发现:无参数原因:实际参数和形式参数列表的长度不同

Can anyone help me understand why this program is not working and whats the cause for this error ? 谁能帮助我了解为什么该程序无法正常工作以及导致此错误的原因是什么?

The issue is that your SubClass_A constructor attempts to implicitly call a parameter-less constructor of SupperClass_A , which doesn't exist. 问题是您的SubClass_A构造函数试图隐式调用SupperClass_A的无参数构造SupperClass_A ,该构造函数不存在。 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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM