current package keyword in java - java

1.Is there a keyword to refer to the current package that you are working in Java. Like we have "this" to refer to the current object. So , is there something similar for a package?
2.Also if the current class that I am working on is in a directory which has other classes,and my class has no package statement, then it will be in the default package. So, is there any way to import rest of the classes in the directory. I know that we can specify the classpath while compiling, but is there any way to do it using imports ?

No, there is not
No, classes in the default package can't be imported. That's one of the reasons you should never put your classes in the default package. The obvious reason is that, if every library did that, you would end up with conflicts between classes.

The first one
No keyword like this to get package name, but you can get package name by java reflection, like the following code
package com.netease.unitest.controller;
public class GenTest {
public static void main(String[] args) {
System.out.println(GenTest.class.getPackage().getName());
}
}
the output is
com.netease.unitest.controller
you can get more details in the following link
http://tutorials.jenkov.com/java-reflection/index.html

Related

Cant use a public method from another class in java

I am trying to call a public constructor of a public class located in one package of my project from the main class, located in a class from another package different to the first one, but located in the same project.
I have understood that the public modifier grant you access to methods from any location inside or outside the package, so i just try to create and instance a new object of the public class first mentioned.
F.E: I try something like.... ClassName newObject = new ClassName(); from the main class
Actually, in order to be able of using that (im using netbeans IDE) I need to import the class/method I want to call, even if they have the public modifier.
My question is... is there a way of using these methods without the need of importing them to the main class ?
I am new in this webpage, so sorry if there is anything wrong with the question.
Qualification and visibility have little to do with eachother. Those are different concepts.
Visibility (enforced by access modifiers like public, protected, private and package-private) is about which class may access (i.e. call or use) it.
Qualification is about the compiler asking you: "Okay, you are mentioning a class name, but there could be thousands around with that name. Which one do you mean?"
You could use the fully qualified class Name instead.
a.b.c.MyClass myClass = new a.b.c.MyClass();
Also see
Java: import statement vs fully qualified name?
Java compiler restricts its search for classes inside the package only. In order to make use of any class belonging to a different package, you have to import it explicitly. You can read more about packages here.
Access specifiers are more from restricting the methods from being accessible by outside world. These access specifiers enforce further restrictions on top of what is enforced by packages. You can refer to this link for access specifiers.

Can one java class/file be part of more than one package?

I'm a relative beginner to Java, and I was just learning about packages and access restrictions, so I was wondering if it was possible to have one Java class belong to more than one package.
I don't mean sub-packages.
Technically you can have a same class with same content in two different packages but then when you use these 2 classes in another Java class then you would have to be very specific (absolute package name) when using either of the class.
Let me give an example ...
Here is class Testing which has exactly same members but are defined in two different packages i.e. com.overflow.stack and com.stack.overflow.
When they are used in an another class Test, you have to import both of them and use absolute package name for at least one of the Testing class so that Java compiler understand which instance is which class (alternatively you can use absolute package name for both the Testing class instances).
--
package com.overflow.stack;
public class Testing {
public void whoAmI() {
System.out.println(this.getClass().getCanonicalName());
}
}
--
package com.stack.overflow;
public class Testing {
public void whoAmI() {
System.out.println(this.getClass().getCanonicalName());
}
}
--
package com.stackoverflow;
import com.overflow.stack.Testing;
public class Test {
public static void main(String[] args) {
// not using absolute package name
Testing test1 = new Testing();
test1.whoAmI();
// must use absolute package name if want to use Testing class
// from different package then above.
com.stack.overflow.Testing test2 = new com.stack.overflow.Testing();
test2.whoAmI();
}
}
Sample Run:
com.overflow.stack.Testing
com.stack.overflow.Testing
That being said, if you or your team or organization is the author of this class then you should avoid having copies of classes in different packages as it will lead to redundant code duplication and will be very confusing for the consumers of these classes. Also it is highly possible that these copies will get out of sync and possibly lead to RuntimeException which are difficult to debug and can crash the application.
No, it cannot be.
But however there can be classes with same name in different packages, but no two similarly named classes in the same package.
You cannot put package declaration twice in the same class.
The package statement must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
However you can define same classes - same name and even same implementation in two packages but package name must be different.
Read more about packages here
You can declare a class with the same name in other packages.
It's not best practice of designing an application.

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}

Why did my import fail in Java?

I hava a StdDraw.java under the same folder of my working file, and picture() is a method within StdDraw.java.
However, I failed adding this line to import the method, suggesting by
package StdDraw does not exist
import StdDraw.picture
How could I possibly do that? Using package? Setting path? Or any modifications? I came from python and find it a little bit weird.
You can't import non-static methods (only classes and static members), and you don't have to!
If both your classes live in the default package then you should be able to do the following without any import statements :
myStdDrawObject.picture(); // if picture is non-static
or
StdDraw.picture(); // if picture is static
Note also, that you can't use static imports on classes that live in the default package.
If you are importing into the class which is there in same package then we no need to use any import.
if you want import mthods into the class use like below. You no need to put method name at the time of the import.
import packagename.StdDraw;
After importing your class, all non static methods of the class are available into the imported class.
when should you use static import? Only use it when you'd otherwise be
tempted to declare local copies of constants, or to abuse inheritance
(the Constant Interface Antipattern). In other words, use it when you
require frequent access to static members from one or two classes. If
you overuse the static import feature, it can make your program
unreadable and unmaintainable, polluting its namespace with all the
static members you import. Readers of your code (including you, a few
months after you wrote it) will not know which class a static member
comes from. Importing all of the static members from a class can be
particularly harmful to readability; if you need only one or two
members, import them individually. Used appropriately, static import
can make your program more readable, by removing the boilerplate of
repetition of class
names.
Read more about static import:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
When importing the package you do not need to import non static methods. You can read on Java - Packages here. It is easily explained and I found it useful when learning the same concept.
Even if you do not include import for the class which is present in the same folder, then also you can create object and call method of that class and also static methods.
You can create object and call the non-static methods.
StdDraw drawObj = new StdDraw();
drawObj.picture(); // if picture is non-static method
For static method, you can call it using class name only.
StdDraw.picture(); // if picture is static method.
What I recommend is to read up on packages and how code is organized in java. It is in someway similar to python, where a directory structure is used, but more to it in java. Maybe this will help
Java Tutorial- Packages

Write a Java class to use in another Java class

I'm a Java noob.
Here's what I'm trying to do:
//File 1
public class Class1
{
//....does some stuff
}
//File 2
public class Class2
{
//..also does some stuff including:
Class1 c = new Class1();
}
File 1 and File 2 are in the same directory.
To compile, I'm using the command:
javac Class2.java
This is giving me errors of the form:
Error: Cannot find symbol Class1
How do I solve this?
If the two files Class1.java and Class2.java are in the same directory, (and assuming you have declared the class you want to use as) you do not need to do any import at all in order to use one from the other; Java will find the other class automatically.
So in Class2.java you can simply do:
public class Class2 {
void someMethod() {
Class1 c = new Class1();
}
}
On base class,
package ABC;
public class PQR {
// Do stuff
}
import ABC.*;
class XYZ {
// Use the PQR class method
}
Assuming they are in the same folder, you shouldn't have to import, if they aren't then you need to specify the package like import java.util.Scanner;. In Java you don't suffix with an extension.
What are you using to write your code in?
not sure I understand the question - are you trying to use an inner class (one class definition inside another class definition) or are these classes separate and independent? imports are required to define the packages/ classes you would have an access to, the ones in the same package are available by default. So if these are in the same package, you don't really need any imports. Also, both these classes need to be visible to each other. When you say it doesn't work, what error do you get?
one way to use inner classes is e.g. outer.new Class1() (where outer is an object of the class that encapsulates Class1). If these are not inner classes, they need to be in separate .java files.
Btw, it is always recommended to provide an access modifier (public, private, protected) explicitly.
Full code listing with error messages would help me give a better answer...
For using multiple classes in one file take a look into this tutorial
If you are writing your classes in two different files and they are in the same package it doesn't require to import them in order to use it. But if you are compiling them manually (using command prompt) make sure you have compiled all the .java file. Otherwise you will get errors.
If you are writing them in different package make sure these classes are public in order to use them. And yes in this case you have to import the package containig the class that you want to use. Again make sure all the classes are compiled if you are using command promt.
My suggestion is to use a good IDE (there are many :)) for doing your code because they assist you much more than we do :)

Categories