0

我不明白下面的程序。我已经提到了我在代码中遇到的两个错误。但我无法理解原因

import java.io.*;
class sdata
{
    float per;
    int m,tm=0,i,n;

    sdata(int n)throws Exception
    {
       DataInputStream dis2=new DataInputStream(System.in);
       for(i=1;i<=n;i++)
       {
        System.out.print("enter marks of subject"+i);
        int m=Integer.parseInt(dis2.readLine());
        tm=tm+m;
       }
       per=tm/n;
    }
}

class disdata extends sdata
{
    //below line gives an error "constructor sdata in class xyz.sdata cannot be applied to given types required:int found:no arguments"

    disdata() throws Exception{             
      System.out.println("TOTAL MARKS OF SUBJECTS:"+tm);
      System.out.println("PERCENTAGE OF STUDENT:"+per);
    }

}
class sresult
{
    public static void main(String args[])throws  Exception
    {
       DataInputStream dis=new DataInputStream(System.in);
       int n=Integer.parseInt(dis.readLine());

       disdata objj=new disdata();
       //the below line creates an error saying "cannot find symbol" 
       objj.sdata(n);
    }
}
4

4 回答 4

2

如果你super class有一个overloaded argument constructor你的子类必须打电话explicitly

disdata() throws Exception{             
     super(some int vale youwanna pass);
            System.out.println("TOTAL MARKS OF SUBJECTS:"+tm);
        System.out.println("PERCENTAGE OF STUDENT:"+per);
    }

记得super()应该是first line中的disdata() constructor

disdata objj=new disdata();
    //the below line creates an error saying "cannot find symbol" 
        objj.sdata(n);

constructor不是方法。您正在尝试使用 objj 调用构造函数 sdata(n) 这是错误的。使用 new 运算符来调用它。像:

disdata objj=new disdata(n);
于 2012-11-02T10:08:40.790 回答
1

Java 强制构造函数的正确链接。构造函数主体中的第一条语句必须是this(...)(对同一类的另一个构造函数的super(...)调用)或(对超类构造函数的调用),如果您不包含显式调用,那么 Java 会插入一个隐式调用super()在构造函数主体的其余部分之前。由于您sdata没有无参数构造函数,因此无法编译。

你需要要么

  1. 将无参数构造函数添加到sdataor
  2. super(0)调用作为构造函数中的第一件事disdata来调用现有的单参数超类构造函数。
于 2012-11-02T10:17:37.507 回答
0

您不能将构造函数作为普通方法调用,而您尝试使用objj.sdata(n);. 构造函数不是方法。

于 2012-11-02T10:10:32.793 回答
0

sdata是超类,disdata当您创建不带参数的 disdata 对象并且在disdata构造函数中您没有调用sdataint 构造函数时,默认情况下它将尝试查找不可sdata用的无参数构造函数,因此会出错。

您可以从构造函数调用sdataint 构造函数,或者在.disdatasdata

class sdata {
    float per;
    int m, tm = 0, i, n;
    sdata(int n) throws Exception {...}
    //No argument constructor
    sdata(){}
}
于 2012-11-02T10:12:37.613 回答