Is it possible to access a method or an attribute from a class which is not in the same package? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Is it possible to access a method or an attribute from a class which is not in the same package?

18th Apr 2019, 8:15 PM
Preet
2 Answers
+ 1
Yes but then you have to use the public access modifier, and you have to import the class: import packageName.className; A small example.. Lets say this is your main class: import secondclass.SecondClass; public class TestOnly { public static void main(String[] args){ SecondClass s = new SecondClass(); s.aMethod(); } } And lets say this class is in another package: // make the class and method public // else you wont be able to access it public class SecondClass { public void aMethod(){ System.out.println("From class SecondClass"); } }
18th Apr 2019, 9:11 PM
JavaBobbo
JavaBobbo - avatar
+ 1
You need to import the package/element you want to use
18th Apr 2019, 9:14 PM
Tomasz Rudzki