Last active
March 5, 2024 10:31
-
-
Save sivaprasadreddy/9843a5ead71803403dbb94f46956324d to your computer and use it in GitHub Desktop.
Java Package Visibility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sivalabs.component_a; | |
//This is package-private, can't be accessed from outside of "com.sivalabs.component_a" package | |
class Mapper { | |
public String toUpper(String input) { | |
return input.toUpperCase(); | |
} | |
} | |
----------------------------------------- | |
package com.sivalabs.component_a; | |
import java.util.List; | |
import java.util.stream.Stream; | |
//This is a public package, can be accessed from anywhere. | |
public class ServiceA { | |
private final Mapper mapper; | |
public ServiceA(Mapper mapper) { //Intellij IDE also shows warninng "Class 'Mapper' is exposed outside its defined visibility scope " | |
this.mapper = mapper; | |
} | |
public List<String> findAll() { | |
return Stream.of("a", "b", "c") | |
.map(mapper::toUpper).toList(); | |
} | |
} | |
----------------------------------------- | |
package com.sivalabs.component_b; | |
import com.sivalabs.component_a.ServiceA; | |
public class ServiceB { | |
private final ServiceA serviceA; | |
public ServiceB(ServiceA serviceA) { | |
this.serviceA = serviceA; | |
} | |
public void printAll() { | |
serviceA.findAll().forEach(System.out::println); | |
} | |
} | |
------------------------------------------- | |
package com.sivalabs.component_b; | |
import com.sivalabs.component_a.Mapper; | |
import com.sivalabs.component_a.RepoA; | |
import com.sivalabs.component_a.ServiceA; | |
import org.junit.jupiter.api.Test; | |
class ServiceBTest { | |
@Test | |
void testPrintAll() { | |
Mapper mapper = new Mapper(); //Can't access Mapper from component_b package | |
ServiceA serviceA = new ServiceA(mapper); | |
ServiceB serviceB = new ServiceB(serviceA); | |
serviceB.printAll(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related Twitter Discussion: https://twitter.com/sivalabs/status/1764897093540618326