Write a Java class to use in another Java class - java

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 :)

Related

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.

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

Importing own file into Java class

Okay, not sure if this would work.. but would it be possible, to use my own Java file that has certain required methods in it, to be imported into my Java class just like any other import? Or does it have a special way?
If your Java file contains a proper Java class enclosing the methods mentioned above, and it is visible to the compiler (i.e. either its source file is on the compiler source path or its class file is on the compiler classpath), you can just import it like any other classes.
Have you tried it? Do you have any specific problem?
If that method is static and visible in your scope, you can use import static. It will make the imported static method look like it is in your class. For example, if your code parse a lot of integers, you can use
import static Integer.parseInt;
And then the parseInt method will be visible and invokable directly:
int parsed = parseInt("123");
That is only required if your other class is in a different namespace. if they are in the same namespace (this includes the default empty namespace), and you 'tell' the compiler about both files, you don't need to use import statements.
If however class A is in namespace org.example.stuffA, and you want to use it in class B in org.example.stuffB, you'll need to use a import org.example.stuffA.A statement, or hard-link it in the document (new org.example.stuffA.A() for example).
In the namespaces example, you still need to make sure the compiler is able to find the required classes. In both cases you also need to make sure the methods you need are of the correct permission type, they would probably need to be public.
You Can use Static methods or by create Object of it & Use.
public class abc
{
public static MyMethod()
{
// ..
}
}
public class pqr
{
abc.MyMethod();
}
Another Way
public class abc
{
public void MyMethod()
{
// ..
}
}
public class pqr
{
abc Obj=new abc();
Obj.MyMethod();
}

Extending custom classes and using them in Java

I'm just learning Java... I have 2 custom classes. One is a Fraction and another is a Matrice that uses Fraction.
I'm using Eclipse, and created both classes from scratch via file->new->class (and default settings).
I'm wondering how can I use these two together in my main program? Like, when I try to add the classes to my project (it was unsuccessful but also) the Matrice class broke.
I also put the Fractions class (.class and .java) in a higher hierarchy of directories with no success (put Fractions in com.myfolder and Matrices in com.myfolder.myotherfolder and specified package com.myfolder and package com.myfolder.myotherfolder respectively).
So really, I have no idea what I'm doing here. I'm doing Java on my own, so I get stuck on a lot of the things like this. My question is, how do I:
Make real classes I can use in the future (object classes or whatever you call them; like I would call a new instance of Fraction/Matrice),
Make custom classes that extend other custom classes,
Use my custom classes in a project.
I've googled it but had no luck. Many thanks in advance.
a) Just write them and probably provide a custom constructor. Then create instances using the new keyword.
b) You used the correct keyword: extend(s):
class MyCustomClassB extends MyCustomClassA { ... }
c) Make sure the classes are on the classpath and use the import keyword to import them into classes that use them and are not in the same package:
package com.myfolder.myotherfolder;
import com.myfolder.Fraction;
public class Matrice { ... }

current package keyword in 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

Categories