Skip to content

Instantly share code, notes, and snippets.

@sivaprasadreddy
Last active March 5, 2024 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sivaprasadreddy/9843a5ead71803403dbb94f46956324d to your computer and use it in GitHub Desktop.
Save sivaprasadreddy/9843a5ead71803403dbb94f46956324d to your computer and use it in GitHub Desktop.
Java Package Visibility
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();
}
}
@sivaprasadreddy
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment