Context: Two classes from different packages (Second class in second package inherits class in first package) are connected through inheritance and made a method call to subclass from parent class.
What I did:
Written two classes in two different notepad files and trying executing one after other but was not possible for me to execute and showing error messages and my classes are as follows:
package first;
import second.Sample1;
public class Sample {
public static void main(String a[])
{
Sample1 s=new Sample1();
s.dis(1);
}
package second;
import first.Sample;
public class Sample1 extends Sample{
public void dis(int i)
{
System.out.println(i);
}
}
In Eclipse, it is giving output as 1 but in what order I should execute these codes using notepads files. Observed that compiling these classes in any order giving error messages.
Thanks much. :)
You created a cyclic package dependency, which is not a good idea.
Your base class Sample doesn't have to know anything about its sub-classes, and when it does, it is usually a sign of bad design.
Just move the main method to Sample1, and Sample class won't have to import second.Sample1.
Related
I have two packages. The first one contains an empty interface and a class implementing it in a single file ("IThing" and "Thing"). The second one contains another Interface ("IThingUser") which has a function returning an object of the type "Thing".
When both files are part of the same package everything works fine, but if they are in two separate packages the one in package2 cannot access the class defined in the first package.
Package1 contains the following file :
package project.package1;
public interface IThing {
}
final class Thing implements IThing {
private int thingField;
public int thingFieldGetter(){
return thingField;
}
}
And package2 has :
package project.package2;
import project.package1.IThing;
public interface IThingUser {
public IThing someFunction(); // Works fine
public Thing anotherFunction();
// "Thing" is not recognized when the two files are in separate packages.
}
Why does this happen ? Is there a way to fix this issue while keeping this architecture ?
PS : I know the structure of this does not make much sense but I did not code package1 and I have to use it as-is.
The problem is that project.package1.Thing is not visible outside the package project.package1, but public classes must be defined in their own files.
Class Thing has package-private visibility. You wouldn't be able to access it outside project.package1 package until it will be implemented as
public final class Thing implements IThing
So i'm awfully new to coding but i quite like it, i'm really young so i have 0 experience on related stuff.
I'm watching this youtube series about java code and in this episode:
he creates another class and uses it in the main one but im on intelij(not eclipse as he is) and it gave me two errors saying java couldnt find the symbol (my second class);
my code:
package com.company;
public class Main {
public static void main(String[] args) {
tuna tunaObject = new tuna();
tunaObject.simpleMessage(null);
}
Second class:
public class tuna{
public void simpleMessage(){
System.out.println("Another class");
}
}
Your simple message method does not accept parameters, so don't try to pass in any. Instead of calling simpleMessage(null) simply call simpleMessage().
Also either make sure that the tuna class is located in the same package as your main class, or import the tuna class via an import statement above the Main class and below the package declaration. Even if the two source files are in the same physical directory, the Java compiler won't understand which class you are referring to unless you specifically define each class in the same package.
Adjust your second class to:
package com.company;
public class tuna{
public void simpleMessage(){
System.out.println("Another class");
}
}
Wecome to Java.
Maybe you can confirm first that the second class is located in the same package with the Main. And it is better to claim a class in First letter upper-cased format.
I've been working on some problems from Project Euler, and, in the process, have written a lot of useful methods (in Java) that I might like to use in other Java projects. I want to be able to call them in the way that you call a function from java.lang.math, so if I had a method primeFactor() I could call it using MyMathMethods.primeFactor(number). How would I go about this? Would I make some kind of package that I could import? Would I make a superclass that includes all my useful math-y functions and have whatever class I'm working with in a new project extend that? There are probably multiple ways to do this, but I don't know what is best. Thanks in advance.
Mark your utility methods as public static. Package your classes containing those utility methods in a jar. Add/Refer that jar in your project, where you want to use the. Then in your code you can call them in a static way lke : MyUtilityClass.myUtilityMethod();
The best thing for this situation is to work in meaningful packages and make their jar
You can create a package like
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Also on classes
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
You can import them like
import animals.*; OR be more specific import animals.MammalInt;Now you can make the jar file , import it in your project and use its methodYou can eaisly do it by this commandjar cmf MyJar.jar Manifest.txt MyPackage/*.class
For more details about jar creation please see thisAs a side note: Be carefull about visibility of members and functions while packaging itBecause there usage and accessibility matters a lot while we are using them
You could create separate java project with your util classes only and then create jar file and import into any another project.
Simply instantiate the class. Like your example, if you had a class MyMathMethods with the function primeFactor(number) then at other classes, simply instantiate it with something like private MyMathMethods myMathMethods;. Now, to call the function simply do myMathMethods.primeFactor(number); You may need to import its package as well.
False understanding of packages is any class defined within a package is visible to all other classes. Not true from my experience. If you have classes containing utility style methods you want to make available in another class? Simply declare a new instance of the class in the class you need the method in. Like... private MathUtilsClass mathUtilsClass = new MathUtilsClass(): Then any method you want to call from this class uses the new identifier, e.g. mathUtilsClass.greatFunction(); This is stupidly easy and should solve your problem.
Assume, that I have class with static methods only. Will class loader load every imported class when loading class to memory? Or it will only load imports when a method from this would need access to it?
Question is whether class loader loads imports when the class is loaded to memory, or just before some methods want to use them.
If it is the first option I would probably need to divide some of my Util classes, to be more specialized.
I think you can test it as follows:
package pkg1;
public class Test {
static {
System.out.println("Hello 111");
}
public static void meth() {
System.out.println("Hello 222");
}
}
Test 1:
package pkg2;
import pkg1.Test;
public class Tester {
public static void main(String... args) {
Test t;
}
}
That prints nothing.
Test 2:
package pkg2;
import pkg1.Test;
public class Tester {
public static void main(String... args) {
Test.meth();
}
}
Prints:
Hello 111
Hello 222
So, just because you have imported a class does not mean the classloader will load the class into the memory. It loads it dynamically when it's used.
I don't claim to know a lot about the class loader, but if you're talking about import statements then the class loader is irrelevant.
Import statements exist purely to allow the developer to use short class names rather than the fully qualified name of each class referenced in the class being written. The compiler uses those import statements very early on to resolve the names of the referenced classes before a single line of bytecode is created.
In general, the static code block at the top of a class file with a report (i.e. a print statement ) will give you a good idea of when the loading happens in your particular application.
However, when dealing with corner cases, like dynamic classes, inner static classes, or classes off the classpath that are dynamically loaded, you will have to be careful - because these classes might actually be loaded MULTIPLE times in an application.
I have three .java files and I need to get them to work together. I think that I need to add all the classes to a main method but I am not sure if this is correct and if I just add the name of the class and the format.
I figured it out, the three files had a package listed at the top of each. I created a new Java project in Eclipse and then a source folder and in the source folder I created a package with the name that they all referenced. Now it runs. Thanks for all of you help for the Eclipse/Java beginner.
You are right: what you think is not right :P
Java can find the classes that you need, you can just use them straight away. I get the feeling that you come from a C/C++ background (like me) and hence think that you will need to "include" the other classes.
java uses the concept of namespaces and classpaths to find classes. Google around for it.
A little example of how variety of classes can be used together:
// A.java
public class A {
public void sayIt() { sysout("Said it by A!"); }
}
// B.java
public class B {
public void doIt() { sysout("Done it by B!"); }
}
// MainClass.java
public class MainClass {
public static void main(String[] args) {
A aObj = new A();
B bObj = new B();
aObj.sayIt();
bObj.doIt();
}
}
Note that there are no includes/imports here because all of the classes are in the same namespace. If they were not, then you'd need to import them. I will not add a contrived example for that coz its too much to type, but should google for it. Info should be easy enough to find.
Cheers,
jrh
If they are in the same package you do not need to do anything, as they are automatically imported for you, but otherwise you'll need to add import statements before your class declaration.
Once this is done, you can reference static members directly ie ClassB.staticMethod(); or instantiate the class ie ClassB classb = new ClassB();
But honestly, if you are this confused, you need to spend some more time doing tuturials.
http://eclipsetutorial.sourceforge.net/totalbeginner.html
http://download.oracle.com/javase/tutorial/getStarted/cupojava/index.html
http://www.freejavaguide.com/corejava.htm
I am not sure what you mean by "adding classes to a main method". If you want to make use of several classes inside your Java program, just import the needed classes/packages at the beginning and create an instance of each class as you go along.
I learned this from a beginner program called Jeroo
Basically if I want to create a new "Jeroo", I would write the following on my Main method:
Jeroo Bob = new Jeroo();
{ methods... }
So basically:
[class] [customnameofclass] = new [class]