在Java中跨越继承

时间:2012-11-02 10:07:01

标签: java

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

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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

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

你需要

  1. sdata
  2. 添加无参数构造函数
  3. super(0)调用作为disdata构造函数中第一个调用现有单参数超类构造函数的函数。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

sdatadisdata的超类,当你创建一个没有参数的disdata对象时,在disdata构造函数中,你没有调用sdata int构造函数,所以默认它会尝试找不到参数sdata构造函数,这是不可用的,所以它会给出错误。

你可以在sdata构造函数中调用disdata int构造函数,或在sdata中创建一个无参数构造函数。

class sdata {
    float per;
    int m, tm = 0, i, n;
    sdata(int n) throws Exception {...}
    //No argument constructor
    sdata(){}
}