Base class and derived class in package

When I create base and derived classes in the same directory without specifying any package that they compile, but adding them to the package results in an error in the derived class saying that it cannot find the base class character. This error is disappointing since I worked in c before, why are 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();
+3
source share
4 answers

When using packages, you must call your compiler from a directory in the root hierarchy of packages (in your case ~).

So go up one directory and call javac like this:

javac TestPackage/Derived_class.java

Then compilation should work. For execution, you will then use:

 java TestPackage.Derived_class

(but your class does not have any main method yet.)


: ? javac , , . Derived_class TestPackage.TestClass, TestPackage/TestClass.java ( .class) ( , ). , TestPackage.

-

javac -cp .. Derived_class.java

javac . '-d', . javac -help JDK .

, , , javac .

+2

. "default" (uneclared/unnamed), TestPackage TestPackage.

: import TestPackage.Test_class;

0

, , , .

, , ".". (.. dir ). , , , , , .

, , "./Testpackage" ( - ).

A simple solution is to add declarations to the class, as well as move them to a directory that reflects this package, i.e. "./Testpackage". Then call the compiler using "Testpackage / *. Java". If you want the classes to be in the default package, remove the package declarations and move the class back to ".".

0
source

Source: https://habr.com/ru/post/1790261/


All Articles