Search code examples
javaimportpackagewildcardimporterror

Not able to access imported class using * wildcard but able to use same class when imported with full qualified name


  • I am new to java please help me
  • I am having trouble using the * wild card in my import statements
  • I compiled the javatesting1 class using javac -d . javatesting1.java and also got the .class file in test1 package
  • here is my folder structure click on this image
  • When i compile javatesting2 while using import statement with * I am getting the following error
    javac javatesting2.java
    javatesting2.java:2: error: cannot access javatesting1
    class testingclass extends javatesting1
                               ^
    bad source file: .\javatesting1.java
    file does not contain class javatesting1
    Please remove or make sure it appears in the correct subdirectory of the sourcepath.


    javatesting2.java:6: error: cannot find symbol
        System.out.println(a);
                           ^
    symbol:   variable a
    location: class testingclass

    2 errors

Here is my code

    package test1;
    public class javatesting1
    {
         protected int a=45;
         int b=78;
    }
    //I am not able to use the javatesting1 class when i use test1.* instead of test1.javatesting1
    
    // the below code is on another file in the same directory
    import test1.javatesting1;
    class testingclass extends javatesting1
    {
        public void meth1()
        {
            System.out.println(a);
           // System.out.println(b);
        }
    }
    public class javatesting2
    { 
        public static void main(String [] args)
        {
                  testingclass obj=new testingclass();
                  obj.meth1();
        }
    }

Solution

  • Hello and welcome to Stack Overflow!

    Since you are declaring class javatesting1 to be in a package test1, Java expects to find that class in a folder named like the package in order to scan it (using the wildcard). I have tested your code, importing using wildcard *, with a folder structure like this

    folder

    • javatesting2.java
    • test1
      • javatesting1.java

    Try editing your folder structure.

    Also please try do adhere to coding conventions: class names should be named using CamelCase, e.g. JavaTesting1