Thursday 7 January 2021

Module : Accessibility

As you see following module descriptor file, module ‘com.sample.xml’ depends on java.base module and exports the package ‘com.sample.xml.util’ to outside word.

 

module-info.java

module com.sample.xml{
   requires java.base;

   exports com.sample.xml.util;
}

 

Let’s define other module ‘com.sample.transformations’ which depends on the module ‘com.sample.xml’.

module com.sample.transformations{
   requires com.sample.xml;

   exports com.sample.transformations.util;
}

 

As you see ‘com.sample.transformations’ module depends on the module ‘com.sample.xml’, so it can access the types from the package ‘com.sample.xml.util’. But one catch here is that, not everything is exposed from the package ‘com.sample.xml.util’. Access specifiers still play a role in reading.

 

Only public types are accessible in other modules. For Non-public types, traditional access rules still apply.

 

Access Specifier

Class

Package

Subclass

Everyone

public

Y

Y

Y

Y

protected

Y

Y

Y

N

default

Y

Y

N

N

private

Y

N

N

N

 

Accessibility is not transitive

module M3{
	requires M2;
}

module M2{
	requires M1;

	export com.sample.doc.util;
}


module M1{
	export com.sample.text.util;
}

 

 


 

As you see above image, module M2 depends on M1 and M3 depends on M2. However, Module M3 cannot access types from exported package of Module M1 through its dependency on M2. If M3 want to access the types from M1 exported packages directly, then it should specify the dependency on M1 explicitly using ‘requires’ keyword.


 

Alternative way to handle transitive dependencies

Using ‘requires transitive’ we can handle transitive dependencies in much more better way.

 

 

 module M2{
	requires transitive M1;

	export com.sample.doc.util;
}


Since Module ‘M2’ define the dependent module M1 using ‘requires transitive’ keyword, if any module reads M2, it automatically reads M1 too. No need to explicitly define dependency on module M1.



Previous                                                    Next                                                    Home

No comments:

Post a Comment