The difference between (a) import somePackage.someClass;
and (b) someClass object = new someClass();
is that (a) will allow call the methods from the imported class without creating new instances of it, while (b) will create an object using the template class and therefore the methods for the class someClass
will belong to the object object
. So if I want to use a method someMethod()
from someClass
in (b) I'd call it through the object
object. Is it how it works?
But more important thing than just the above options available is when to use which. First type of call is to class methods whereas the second class is to instance methods.
Instance Methods vs Class Methods: Each class represents a set of attributes and behaviour. Instance methods usually represent the behaviour. example if Person is a class and Robb is an object, then robb.weight can be attribute, robb.write() would be an instance method and Person.type() (ans: species) or Person.population (ans: total number of instances) can be class methods.
Also you represent instance methods in textual writing as ClassName#instanceMethod and ClassName.classMethods
No, you are wrong
Simplistically if the class that you want to use is not in the same package
then you need to import it, or fully path the class eg java.util.ArrayList
.
If the methods are not static, then you will need to create a new Instance of the class you want to use.
You can use methods from other class directly only if it is a static method. You will also have to add static in your import statement if you want to use the method name directly without prefixing it will the class name. For non-static methods you have to create instance of the class and then call that method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.