MyNameIsNemo MyNameIsNemo - 1 year ago 75
Java Question

Difference between importing class and subclass

I started learning Java and I am not sure what can I all do when I import class from another package(use methods from that class, variables...?) Is it the same as If I wrote that another class as subclass in the same package? Are there any forbidden things when I import another class? Actually, what it means when I import another class? I am so confused.

Answer Source

Importing a class is pretty much just allowing you to use the class name instead of the fully qualified name. There are also wildcard imports which import the whole package, but using it can cause problems if there are classes with the same name. Two packages, java.lang and the same with your class, can be accessed without fully qualified name even if they're not imported.

So, we can do things like this:

java.util.List<String> list = new java.util.ArrayList<>();

// equals:

import java.util.List;
import java.util.ArrayList;

List<String> list = new ArrayList<>(); // much cleaner option

A class can always see all the fields and methods in the same package unless they're declared as private, while a class in another package can only see public (and protected when extending).

Basicly like this:

private void a() {}    // visible to the declaring file
void b() {}            // visible to the package of the declaring file
protected void c() {}  // similar to above, but also visible to extensions
public void d() {}     // visible to everyone
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download