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

4/18/2019 8:15:33 PM


2 Answers

New Answer


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"); } }


You need to import the package/element you want to use