I have two java classes (.java files). I want to be able to create new instances of an object in one class that were defined in the other class, without referencing the class name each time. In C# there are #using and includes, but I am only able to use import <pre-compiled code> in java. Is there a way to do this:
import TestClass;
and then simply call a function inside it without using
TestClass.TestFunction()
every time? I simply need to have all of my functions and objects to be separate from my Main class.
Assuming TestFunction is a static method in TestClass, you can use a static import:
import static TestClass.TestFunction;
// or
import static TestClass.*;
and then call it without using the class qualifier:
TestFunction(...);
Note this can lead to confusing/hard-to-read code – use static imports sparingly.
If you're using netbeans then you won't be finding any issue during the import of any java classes. And yeah that's true you can have only "pre-compiled classes" as import statement. If you are running on notepad then you need to compile your independent classes first and then your dependent classes. And if you use Netbeans or Eclipse or any other IDE then you do not have to worry they will manage by themselves, you just have to use proper package and class names
You can have two types of imports
import package1.Class1;
import static package1.Class2;
With the first one you can create object of Class1 (or any other class if present in Class1) and invoke the methods
With the second one you can directly call the static methods of Class2 without referencing it with classname
Updated
See tutorials on packages in JAVA
Related
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.
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
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();
I wrote a method public static String timestamp() in a class called Utilities, which I want to call in every System.out.println().
Can you tell me how I can call this method in a different package? For example when I have package XY, with the class XY in it, then I can't call the timestamp() method, which is in the root src folder.
You need to use the whole class name, so as your class is called "Utilities":
Utilities.timestamp();
Will call your method. Remember to import your "Utilities" class at the top of your calling class.
Alternatively, if you want to just call:
timestamp();
You can statically import the class:
import static com.foo.Utilities
You need to import the package containing the class containing the timestamp() method. If you haven't declared a package for the class, you should do it now. After importing you can just use Utilities.timestamp() to call it.
If you're unfamiliar with packages in general, you should see the Oracle tutorials: http://docs.oracle.com/javase/tutorial/java/package/
So, more often than not, utility classes are declared as static. I'll give you an example.
Example
public class Utilities
{
public static String timestamp()
{
// Return timestamp.
}
}
Then in your XY class, you need to import your Utilities class, and you can access it as follows.
Utilities.timestamp();
You can call it using:
Utilities.timestamp();
from any class. Remember to import the Utilities class
It's static so you can just call Utilities.timestamp();
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 :)