gpt4 book ai didi

java - Java 中继承的障碍

转载 作者:行者123 更新时间:2023-12-02 00:09:18 25 4
gpt4 key购买 nike

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

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);
}
}

最佳答案

如果您的父类(super class)有一个重载参数构造函数,您的子类必须显式进行调用。

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() 应该是 disdata() 构造函数中的第一行

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

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

disdata objj=new disdata(n);

关于java - Java 中继承的障碍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13193116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com