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.
Related
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.
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'm not new to Java but I never learned Packages. Anyways, let's say I create a folder called maina.
I put in file main.java in folder maina:
package maina;
import other.Dice;
public class main
{
public static void main(String[] args)
{
System.out.println("Hello world!");
System.out.println(Dice.test);
}
}
Then I create a new folder called other inside the folder maina. In folder other I put file Dice.java:
package other;
public class Dice
{
public Dice() {
String test = "Testing!";
}
}
OK, now Dice.java compiles fine.
However when I compile main.java I get this error:
C:\Users\tekaffi\Documents\ask\maina\main.java:13: cannot find symbol
symbol : variable test
location: class other.Dice
System.out.println(Dice.test);
^
1 error
Tool completed with exit code 1
What am I doing wrong?
Here's the error I get when I compile:
C:\Users\wekaffi\Documents\ask\maina\myMain.java:3: package maina.other does not exist
import maina.other.Dice;
^
C:\Users\wekaffi\Documents\ask\maina\myMain.java:13: cannot find symbol
symbol : class Dice
location: class maina.myMain
Dice myDice = new Dice();
^
C:\Users\wekaffi\Documents\ask\maina\myMain.java:13: cannot find symbol
symbol : class Dice
location: class maina.myMain
Dice myDice = new Dice();
^
3 errors
Tool completed with exit code 1
It has nothing to do with packages.
Your code is seriously messed up, you're trying to call a "test" member on the "Dice" class but you haven't created that member. besides that, you can't have a class named "main" and then have a static main method in it beacuse the compiler will think the main method is the constructor you need to rename your class to something else.
For your code to work your Dice class needs to look like this:
package maina.other;
public class Dice
{
public String test;
public Dice() {
this.test = "Testing!";
}
}
And for the print to work you need to create a new instance of Dice before you print
Either that or you make Dice static. So your main needs to be renamed to myMain and then the class should look like this:
package maina;
import maina.other.Dice;
public class myMain
{
public static void main(String[] args)
{
System.out.println("Hello world!");
Dice myDice = new Dice();
System.out.println(myDice.test);
}
}
If you're placing stuff where you said you are, it should work fine package-wise
Your Dice class must have a package declaration like so
package maina.other;
Your main class should import Dice like so
import maina.other.*;
It'd be package maina.other, if it is in /maina/other
Dice needs a public static string test. The current test is a non-static local variable to the constructor. Or you can make test non-static and then have the constructor set the test member and then do new Dice().test in the main.java
And the package name doesn't matter, foldering is only a convention and is IIRC ignored by the compiler. So thats not the issue here!
When you put package 'other' inside of 'maina' the new package is
package maina.other;
package maina.other;
As a side note, if you're using an IDE like Eclipse, you don't have to make the directories manually - it does it for you. Also navigating your packages with the package viewer is easy.
This one is tough to explain, and you've mentioned that you're new to Java, so please don't let me confuse you.
The package of a top-level type, such as main or Dice is whatever is listed in the package declaration. The package for Dice could just be other, even though the corresponding directory is nested inside the directory that corresponds to package amain.
The key is resource discovery when compiling and running. When you compile, you can specify a sourcepath and a classpath that helps the compiler resolve dependencies. Likewise, when you run, you can specify a classpath that helps the JVM resolve dependencies. There is no restriction that root packages not be nested inside one another. So, both amain and other could be root packages, like so:
% cd <directory-that-contains-amain>
% javac -sourcepath .:amain amain/main.java amain/other/Dice.java
% java -classpath .:amain amain.main
This is considered abnormal (and consequently poor) practice, however. You shouldn't do it, but you could.
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]