Reputation: 289
I am learning inheritance and while doing so on Eclipse, I get an error when trying to run the following program:
import java.io.*;
import java.util.*;
public class singinh
{
void sub(int a, int b)
{
int c = a-b;
System.out.println("Diff is"+c);
}
}
public class singinh1 extends singinh {
int a,b;
void add(int a, int b)
{
this.a=a;
this.b=b;
System.out.println("Sum is"+a+b);
}
public static void main(String args[])
{
singinh1 s = new singinh1();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
s. add(a,b);
s.sub(a,b);
}
}
The error that I get is "Error: Could not find or load main class superex$A"; What is causing this error, and how do I fix it?
Upvotes: 1
Views: 64
Reputation: 71
In java you cannot have more than one public class in the same source file. Also the name of the source file should be the name of the public class in that source file exactly.
Since your main method is in "singinh1" class , keep it as the public class and remove public keyword from "singinh" class. Name the source file name to singinh1.java .
Modified code :
import java.io.*;
import java.util.*;
class singinh
{
void sub(int a, int b)
{
int c = a-b;
System.out.println("Diff is"+c);
}
}
public class singinh1 extends singinh {
int a,b;
void add(int a, int b)
{
this.a=a;
this.b=b;
System.out.println("Sum is"+a+b);
}
public static void main(String args[])
{
singinh1 s = new singinh1();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
s. add(a,b);
s.sub(a,b);
}
}
Upvotes: 0
Reputation: 44965
As you start with java
the best thing to do is to create 2 files singinh.java
and singinh1.java
, move the related code into the corresponding file and launch your java
command using singinh1
as main class.
In singinh.java
you will have:
public class singinh
{
void sub(int a, int b)
{
int c = a-b;
System.out.println("Diff is"+c);
}
}
In singinh1.java
you will have:
import java.io.*;
import java.util.*;
public class singinh1 extends singinh {
int a,b;
void add(int a, int b)
{
this.a=a;
this.b=b;
System.out.println("Sum is"+a+b);
}
public static void main(String args[])
{
singinh1 s = new singinh1();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
s. add(a,b);
s.sub(a,b);
}
}
Then you will be able to launch singinh1
Upvotes: 1