Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parent package class accessible from child packge class in java?

Tags:

java

In java parent package class accessible from child packge class? please explain me any one?

example package A.A1.A2 contains class sub package A contains class sup

Is there anyway to access sup from sub?

pls explain.

i tried import it won't work Example: before the program Directory Structure is package1 contains package1.java --> package2 --> package3 contains PCheck.java

//package1.java
package package1;
public class package1{
    public static void main(String[] args) {

    }
}
class phelo{
    phelo(){
        int a;
        System.out.println("hai fun freom package 1");
    }
}

//PCheck.java;
package package1.package2.package3;
import package1.*;   //to import package1.java
public class PCheck {
    public static void main(String[] args) {
        phelo obj=new phelo();
    }
}
class helo{
    helo(){
        int a;
        System.out.println("hai fun from package 3");
    }
}

output: compile time error:package package1.package2.package3 doesnot exist;

for import class from different directory we use import statements but here we need access parent package from subpackage.i tried import it won't work pls explain with an example.

like image 597
Vinoth Kumar Avatar asked Aug 25 '10 09:08

Vinoth Kumar


1 Answers

Java does not recognize the notion of a subpackage1. As far as Java is concerned packages a and a.b and a.b.c are unrelated. They are just names.

So, if you want to access a.b.SomeClass from a.b.c.SomeOtherClass, you must either use a fully qualified class name, or add an import to SomeOtherClass

1 - From Java 9 onwards you can use modules to implement abstraction boundaries that are larger than a single package. This doesn't address this question which is about package-private access, but it could be viewed as an alternative to package-private.


As for your example that doesn't compile, I think we need a proper MCVE to understand that. My guess is that you have gotten the file organization for your source tree wrong ...

It is also possible that the problem is that the visibility of the class you are trying to import is wrong (package private), but that wouldn't cause the compiler to say that the package doesn't exist, like you said it does.

like image 65
Stephen C Avatar answered Oct 31 '22 17:10

Stephen C