1

I have a subclass (Item) in a java class named (tools) that I would like to use in a few different classes in my app now what I would like to know is what is the difference between using

import com.example.tools;

and creating an instance of the class :

Tools item = new Tools();

do they both get the same results and is one slower than the other or is there a reason why I would use one instead of the other . thanks for your answers.

Amr El Aswar
  • 3,395
  • 3
  • 23
  • 36
  • 4
    Your naming convention is backwards, by the way. Class names should be capitalized -- variable names should not. i.e. `tools Item = new tools();` should be `Tools item = new Tools();`. – Kevin Coppock Dec 08 '15 at 20:44
  • @kcoppock sorry wasnt paying attention while writing will correct that now – Amr El Aswar Dec 08 '15 at 20:47

3 Answers3

5

import just gives you a shortcut to the name of the class. You could (although it's not recommended) not import the class and simply refer to it as com.example.Tools everywhere. new Tools() actually creates an instance of the class, that you can call methods on, etc.

blm
  • 2,379
  • 2
  • 20
  • 24
2

Keep in mind what blm. Furthermore, take a look on basic concepts to help you begin on the right way: http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep

1

Well, your question seems to be a typical Java (or maybe more: object-oriented programming) question. Please, feel free to read this really good article Java - Object & Classes.

I also recommend you read at least parts of this classic programming book: Thinking in Java

Like @blm said, import is just a shortcut to existing object, where new means that you' ve created a new instance of it and 'new Human()' called 'paul' can do what every 'Human()' does.

Remember, that in Android you can't create instance of some main classes like Activity. Too learn more about it visit:

Create instance of new class in Android

Creating an instance using the class name and calling constructor

Community
  • 1
  • 1
piotrek1543
  • 19,130
  • 7
  • 81
  • 94