When I create the base and derived class in the same directory without specifying any package they compile fine, but adding them to a package leads to an error in derived class saying that it is not able find he symbol of base class. This error is frustrating since I have been working in c before , why all these shenanigans in Java?.
package Testpackage; // If I comment this then derived class compiles fine
public class Test_class{
int x,y;
public static Integer angle;
public Test_class(int a,int b)
{
x = a;
y = b;
}
public Integer product()
{
return x*y;
}
}
*************Derived class ****************
package Testpackage; // If I comment this then it compiles fine
public class Derived_class extends Test_class{
Integer vol;
Test_class I = new Test_class(1,2);
public Derived_class(){
super(9,10);
vol = 0;
}
public Integer volume()
{
vol = this.product();
return vol;
}
}
********* output *************
assa@dasman-laptop:~/Testpackage$ javac Derived_class.java
Derived_class.java:4: cannot find symbol
symbol: class Test_class
public class Derived_class extends Test_class{
^
Derived_class.java:7: cannot find symbol
symbol : class Test_class
location: class Testpackage.Derived_class
Test_class I = new Test_class(1,2);
^
Derived_class.java:7: cannot find symbol
symbol : class Test_class
location: class Testpackage.Derived_class
Test_class I = new Test_class(1,2);
^
Derived_class.java:15: cannot find symbol
symbol : method product()
location: class Testpackage.Derived_class
vol = this.product();
When using packages, you should call your compiler from the directory at the root of the package hierarchy (in your case
~).So, go one directory up, and call javac this way:
Then the compiling should work. For executing, you then would use:
(but your class does not have any main method yet.)
Edit: Why is this necessary? When
javacsearches classes referenced from your classes, it searches them according to their package. Your Derived_class referenced the classTestPackage.TestClass, and this would be searched inTestPackage/TestClass.java(or.class) (relative to the classpath, which here consists of your working directory). No such directory exists, when you are already inside of the TestPackage directory.Another way to call it here would be to use
since then javac would search the related classes from the parent directory. You should then also set the ‘-d’ parameter to put generated class files in the right structure. Call
javac -helpfor a summary of the options, or look in your JDK documentation for a more detailed description of all the options.When you compile only a single file, it does not really matter, since the file to compile is given on the command line, and javac does not need to search more files.