Why has object been created without importing class? [duplicate] - java

This question already has answers here:
Java: Use import or explicit package / class name?
(3 answers)
Closed 8 years ago.
I came across some java code where the following statement was present.
com.myproject.bar.Foo foo = new com.myproject.bar.Foo();
The class com.myproject.bar.Foo has not been imported into the class but an object of Foo is created in the class where this statement is written.
Why has such an implementation been done? Are there any advantages of using such an implementation over doing an import of the class Foo?

It's instantiation with the fully-qualified name of the class.
com.myproject.bar.Foo foo = new com.myproject.bar.Foo();
This doesn't require to add an import statement, because you've already told the compiler which is the package of the class you want to instantiate.
Sometimes this is used when there are several classes with one and the same simple name.
If you'd like to do this:
Foo foo = new Foo();
then you will have to import the class:
import com.myproject.bar.Foo;

An import statement just makes the type available by its short name without specifying the package. That's all it does. It's not like the class can't be used without an import.
Usually it's clearer to use an import instead, but sometimes that's not possible - you may want to use two classes both called Foo from different packages with the same class, for example. (This is most common when you've got two representations of the same entity - an API representation and a storage representation, for example.)
Without knowing what the real code looks like, we can't tell whether that was the case here, or whether an import would have been fine. If it can work, an import is usually more readable.

If you address the class with fully qualified name such as com.myproject.bar.Foo, you need to specify it every time when you try to access that class.
But in case of import, you dont need to.
That's one of the advantages.

com.myproject.bar.Foo is absolute class name.
Foo is just the Class name(relative) and it can be in any package, so to specify the package, import statements are used.
In cases where you have more than one class with same name, you have to use the absolute class name in your code to distinguish between the duplicate names. Example com.Foo and org.Foo then you use Foo for com.Foo and org.Foo for org.Foo.

There is no special advantages.
But useful in case if two classes have same class name and belongs to different packages then you need to specify the fully qualified package name to differentiate both while using them in a Class.
Consider 2 classes
com.myproject.bar.Foo
com.myproject.bar.innerbar.Foo
Now in some other class you are going to instatiate like
Foo foo = new Foo();
Which Foo to import now?
To avoid that ambiguity, we need to specify the full package name.

Related

How does Java know which class to use in this example?

I am beginning to learn the principles of OOP and inheritance, and I came across this question while writing some code:
Suppose there is a package which contains a class called ClassA. Then, in a separate folder, I have another class called MyClass. Inside the same folder as MyClass, I have another class called ClassA, which is unrelated to the ClassA in the package. When I write the code for MyClass, I make it extend ClassA.
Which ClassA does MyClass extend from? Does MyClass inherit the ClassA which is in the imported package, or does MyClass inherit the ClassA which is in the same folder as MyClass? Would the code even compile?
I am trying to understand this from a theory perspective before diving into examples.
what you're looking at is a Statically scoped language which will work its way out of its inner scope, all the way to its outter scopes.
In this case, since import Class A is declared directly inside the file to which it is first called, it will use import Class A and stop.This will be its default behavior.
It will not carry on to look at the packaged Class A because it found one already, declared inside of the same class file.
This is the default behavior of java's (static) scope hierarchy.
IF it had not found an import of Class A imported inside the same file, it would reach out to its package to search for one.
This is very useful when declaring like variables. Do a little research how statically scope languages work.
If it is easier for you to understand, you can be explicit in your intentions by declaring exactly which Class A you would like though.
Just a side note- this is more of a programming languages question than directly a java question, but since you ask specifically for java, we only need to cover the simple specific answer. if you would like to know more, i can direct you (or tell you) more about statically vs dynamically scoped languages.
I suppose it is worth noting that if you decide to import both Class As even from your package (which you do NOT need to do) you would have to explicitly declare which you would like.
In that situation, to make it perfectly clear to the compiler you would probably want to do something like extends otherPackage.ClassA, and use the full reference name to extend the classA from the other package. If you want to use the one from the package MyClass is in, then just don't import the other ClassA and do extends ClassA
Since you're new to programming, I'm going to explain it in really simple words. Say there is a package called Salads. In that package, you have a class called Caesar. Then, you have another package called People. In that package, you have another class called Caesar. Obviously, Salads.Caesar refers to Caesar salad, and People.Caesar refers to a person named Caesar. But both classes have the same name: Caesar.
So when you're writing java code, java looks in two places for class definitions:
classes defined in the same folder (because they are implicitly in the same package if they are in the same folder assuming you're following all the normal rules.
classes defined in any imported packages
So the question is asking if you just say Caesar in the code, will it recognize it as the one in the same folder or the one in the imported package? Well, this is a bad question to ask because first of all, you should not name your classes so ambiguously. Secondly, if it can't be helped, you should always refer to the fully qualified name in your code.
If you mean People.Caesar then type People.Caesar and if you mean Salads.Caesar, type Salads.Caesar. Don't take shortcuts. You can only take shortcuts if there is no ambiguity. The compiler will probably complain about it anyway asking you to specify. AKA your code will not work unless you change all references of Caesar to Salads.Caesar or People.Caesar.
Packages in Java is a mechanism to encapsulate a group of classes,
interfaces and sub packages. Many implementations of Java use a
hierarchical file system to manage source and class files. It is easy
to organize class files into packages. All we need to do is put
related class files in the same directory, give the directory a name
that relates to the purpose of the classes, and add a line to the top
of each class file that declares the package name, which is the same
as the directory name where they reside.
in the top of java files, you have import that you can choose what class from what package you mean of course as #Jason said too if the class you want its in your package you don't need to tell it explicitly and compiler know that but if its in another package you have to tell him explicitly.
assume you have FirstClass.java in src folder and another in mycodes folder when in your class you import FirstClass you mean FirstClass.java that exist in src folder and when you import mycodes.FirstClass you mean FirstClass in mycodes folder.
your class can be member of packag.when you extend class that you class are in package A when you extend SomeClass you mean SomeClass that is in package A and if you want extend other class that is in other package like B you must extend B.SomClass
Here is another information about packages in java

Can import statements be used anywhere besides the beginning of a Java file?

In python, the import statement can be placed everywhere in the file, even inside a class, or an if.
Is there a way to accomplish the same thing in Java? I understand that it could be a bad practice not to put all the imports at the top of the file, I'm just wondering if it is possible in some way or not.
The very first statement in a Java file must be (if there is one) the package statement, followed by the import statements. They can not be placed in another location.
However, it is possible to skip the import altogether by using fully qualified class names (which I personally don't recommend). You need to use them everywhere you would have used the short, unqualified name.
import my.package.MyClass;
public class Test{
private MyClass instance = new MyClass();
}
can be rewritten as:
public class Test{
private my.package.MyClass instance = new my.package.MyClass();
}
According to the documentation here:
To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one.
So it seems that it is not possible.
Short answer : No it's impossible !
The import statement must be in the top of the file after the package statement (if exist).
You must know : You can use your imported class/interface or static method in all classes/interfaces in the same file including inner/nested classes.
There isn't a way, except maybe messing with bytecode if you count that. I suppose the best equivalent would be writing the fully qualified name of what you're looking to use.
Not sure why you would want to though.
No. They need to be at the top, after the package declaration.
An ordinary compilation unit consists of three parts, each of which is
optional:
A package declaration (§7.4), giving the fully qualified name (§6.7) of the package to which the compilation unit belongs.A compilation unit that has no package declaration is part of an
unnamed package (§7.4.2).
import declarations (§7.5) that allow classes and interface from other packages, and static members of classes and interfaces, to be
referred to using their simple names.
Top level declarations of classes and interfaces (§7.6).
This doesn't do a great job at conveying that the ordering of each part is strictly enforced, but the formal grammar does make this clear:
OrdinaryCompilationUnit:
[PackageDeclaration] {ImportDeclaration} {TopLevelClassOrInterfaceDeclaration}

Java import statements

I was reading about predefined methods and was learning about import statements. I have seen and often times used these to use certain predefined methods, but I've always seen them placed at the very beginning of a program. My question is, can these be placed inside a certain block of code so that it is only seen in that block? I'm not sure that there would ever actually be a reason for this, mostly just curious.
java files contains three parts:
package definition
imports definitions (optional)
the class (or interface/enum) definition.
and it also has to be in this order, you'll get compilation error if it's not in this order
No, you need to define it before of the class/interface, after the package statement.
So an import is always visible to the entire .class-file.
import lets you use members of other packages than your local package, without specifying the full name of a class (e.g. either you need to import java.util.List, or you need to use it's full name everywhere).
There is a tutorial on using package members by Oracle.
The order in a .class-file is defined as:
package specification (optional)
import statements
class / interface / enum definition
My guess is that will give you a compiler error. BUT you can effectively acheive the same thing if you specify the full package name of a class when you instantiate it.
E.g:
public String getString() {
return new com.package.some.Class("hello world").toString();
}
In this case you don't need to have an 'import' directive at the top of the class because you are telling the compiler inside the method that the class you want is located in the com.package.some package and the class is called Class.
This actually happens in the wild when for example you have to classes in different packages that have the same name. You can only import one of them, the other one you will have to inline the package definition inside the code.
import com.package.some.Class;
public class Yolo {
private Class classA;
private com.package.other.Class classB;
public Yolo(Class classA, com.package.other.Class classB) {
this.classA = classA;
this.classB = classB;
}
}
you can't just import both 'Class' objects and refer to them as Class because the compiler won't know which one. So, this is a valid situation where you will see this kind of thing happen for real.
From Oracle Docs :
Importing a Package Member
To import a specific member into the current file, put an import
statement at the beginning of the file before any type definitions but
after the package statement, if there is one. Here's how you would
import the Rectangle class from the graphics package created in the
previous section.

java package vs System in JAVA

I am just learning JAVA (again in a very long time) and I have a simple question. What is the difference between java.something and System.something?
The beginner book I got is not thorough enough to explain this (at least not yet).
In the case of java.something, this is a package: a package contains various classes that are available for use in your program. If you want to use a particular class--say, java.util.Random--you can either refer to it in full as java.util.Random, or have an import line at the top of your class that tells Java where to find the Random class, and then refer to it just as Random.
System is a class, and it's contained in the java.lang package. (And java.lang classes are always imported into your project, so you don't need the import line in this case.) When you refer to System.something(), you're referring to the System class, and invoking the something() method of that class.
Most of the time, if you want to invoke method something() on class Someclass, then you create an instance of Someclass and then call something() on it:
Someclass x = new Someclass();
x.something();
but for a static method, you invoke it without needing to create an instance. The methods of System are static, so you just invoke them as
System.something();
without creating an instance of type System.
In Java, classes and interfaces are organized in packages (<- click to go to the tutorial).
Class System is one of the classes in the package java.lang.
If you see for example System.out, it means you are doing something with the member variable out which is part of class System.
When you see for example java.util.Date, then it means you are using the class Date which is in the package java.util. You can either use the fully qualified name of the class, which is java.util.Date, or you can import the class and then just use the class name Date:
// At the beginning of your source file
import java.util.Date;
// Now you can just use the short name Date instead
// of the long name java.util.Date
Date now = new Date();
Hard to tell, but System.something is really shorthand for java.lang.System.something. You're referring to the System class in the JDK.
If you see java.something, it's going to be a package name built into the JDK (e.g. java.sql, java.util, etc.) That's reserved by Sun/Oracle for JDK packages.
System class belongs to java.lang package and all classes in the java.lang package are imported by default so you do not need to import java.lang.*;
On the other hand to use class from java.something package you must write package name with class name
Object obj = new java.something.YourClass();
or you must use import statement
import java.something.YourClass;
...
Object obj = new YourClass();

Java: Use import or explicit package / class name?

I'm writing a very basic app, extending the Swing JFrame. What are the differences between making an explicit reference:
public class LineTest extends javax.swing.JFrame {
...
or importing the class beforehand:
import javax.swing.JFrame;
public class LineTest extends JFrame {
...
When (and why) would you use one technique over the other?
There is no real difference; the generated byte code will be exactly the same. An import statement is really just a way to tell the compiler "when I write JFrame, I actually mean javax.swing.JFrame".
You might want to use fully-qualified package names if you have for example two classes with the same name in different packages. One common example from the standard library are the classes java.util.Date and java.sql.Date.
The only difference is in the source code. Using the fully qualified name leads to less readable code, so everyone uses imports pretty much exclusively. The only place where I've ever seen the fully qualified names used consistently is in generated code.
The only reason to use the fully qualified name in regular code is when you have to use two classes with the same simple name (e.g. java.util.List and java.awt.List) - in that case there is no alternative.
For the compiler it doesn't make any difference. The disadvantage of using the full qualified name is that you would have to write it each time you are using the class. I only use the full qualified name if I have two classes with the same name in different packages. This way you can differ between those two classes

Categories