Reputation: 5628
I dont understand the program below. I have mentioned the two errors I have encountered in the code. But I cannot understand the reason
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);
}
}
Upvotes: 0
Views: 121
Reputation: 122364
Java enforces proper chaining of constructors. The first statement in the body of a constructor must be either this(...)
(a call to another constructor of the same class) or super(...)
(a call to a superclass constructor), and if you don't include an explicit call then Java inserts an implicit call to super()
before the rest of the constructor body. Since your sdata
doesn't have a no-argument constructor this fails to compile.
You need to either
sdata
orsuper(0)
call as the first thing in the disdata
constructor to call the existing single-argument superclass constructor.Upvotes: 1
Reputation: 46398
if your super class
has an overloaded argument constructor
your subclass has to make a call 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);
}
remember that super()
should be the first line
in the disdata() constructor
.
disdata objj=new disdata();
//the below line creates an error saying "cannot find symbol"
objj.sdata(n);
constructor
are not methods. you are trying to call the constructor sdata(n) with objj which is wrong. use new operator to invoke it .
like:
disdata objj=new disdata(n);
Upvotes: 2
Reputation: 41200
sdata
is super class of disdata
and when you are creating a object of disdata with no argument and in disdata
constructor you did not call sdata
int constructor so by default it will try to find no argument sdata
constructor, which is not available, so it gives error.
you can do thing call sdata
int constructor from disdata
constructor or crate a no argument constructor in sdata
.
class sdata {
float per;
int m, tm = 0, i, n;
sdata(int n) throws Exception {...}
//No argument constructor
sdata(){}
}
Upvotes: 0
Reputation: 23655
You cannot invoke a constructor as a normal method, which you try to do with objj.sdata(n);
.
Constructors are no methods.
Upvotes: 0