Learning java newly. Can anybody clear my doubt in following?
My demo application has code like this
SourcePackages ---> ex1.pkg1
|
--->food
My ex1.pkg1 has one class called Ex11 and it contains the main function.
My food package contains one abstract class fruit and another subclass of class fruit as Apple.
I am creating an instance of Apple class in my main function in class Ex11.
The code compiles fine and runs also fine. But I am trying to understand the directory structure in java.
When I run the program I can see the following folders inside the build/class directory
ex1 -> pkg1 -> Ex11.class
food -> Apple.class and fruit.class
fruit -> empty
I don't understood why the directory fruit is created although I don't have any package named fruit? Even if I delete it and compile again its not created. But created when I run the application.
Extra Info - I am using netbean IDE
To answer your question Not exactly. You can create same directory structures ( hence same package) in different locations and even in different jars. For example; you can have directories CoreDomain\com\example and CoreServices\com\example. Now, classes within these two directories will have same package com.example even though they are in different directories ( but same directory with ref. to starting point ; as both are in com.example )
Related
Suppose i have a directory "Animal" (without quotes) and i have java classes in it.How to add that directory to class path in Linux ? I mean suppose i want to use class files in "Animal" directory from some other folder , then i need to add "Animal" to class path .How to do it ?
Also suppose Animal directory has several sub directories and each of the sub directories also have directory having java class files .Then how to add each of them to java package ?
edit : Suppose i have two folders in Ubuntu say Downloads and Documents .Now in Downloads i created a folder called "animal" having a class named Dog.java . Now in Documents folder i created main method in which i try to make an instance of "Dog" class .I want to do it by importing the package "animal" in Download folder. How to do it ?We know that if we want to use some pre-built package in java then we import that package to use classes inside that package .Similarly suppose i want to import my own package , what i need to do ? When i write import and compile then it says package "animal" does not exist .So what i do so that it doesn't gives compilation error .Can some one elaborate by giving an answer .
I did lot of work before asking this question and when i was unsuccessful i finally asked this question .
To work this out in detail, with some code- the folder structure is:
~ (user folder)
~/Documents
~/Documents/useanimal
~/Documents/useanimal/UseDog.java
~/Downloads
~/Downloads/animal
~/Downloads/animal/Dog.java
The code for the two classes is below. To compile:
cd ~/Downloads
javac animal/Dog.java
cd ~/Documents
javac -cp ~/Downloads useanimal/UseDog.java
To run:
cd ~
java -cp Documents:Downloads useanimal.UseDog
and it will output
UseDog:main
Dog created
Code:
animal/Dog.java
package animal;
public class Dog {
public Dog() {
System.out.println("Dog created");
}
}
useanimal/UseDog.java
package useanimal;
import animal.Dog;
public class UseDog {
public static void main(String[] args) {
System.out.println("UseDog:main");
Dog dog = new Dog();
}
}
I have developed eclipse plugin which for any given java project create GUI in form of package structure. I have successfully run my plugin for different java project.
Now, I thought should try my code in some open source project, therefore, I download JDOM Framework.
However, I found that the JDOM source code has this structure.
JDOM -> contrib -> src -> java -> org -> jdom2......
where as i assume that the project will have always below structure
Project Name -> Src -> PACKAGE NAME STARTS HERE.....
I load the classes using below code,
IPackageFragment[] packages = javaProject.getPackageFragments();
for (IPackageFragment mypackage : packages) {
if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
// unit.getPath().toString() give me path, but how to extract only class name with package
// save it in to MAP with Package as key
}
}
}
Now, I want to show classes with only package name, therefore, I remove first two string (PROJECT NAME, SRC), but this cannot be always the case as for JDOM Framework.
Therefore, how can I get only package name along with class name using my method above? Or should I use different mechanism?
Looking at the directory structure alone seems to be an awfully error-prone way to go about it. Who knows how deep the directory tree goes? If instead you scan for Java source files, you should be able to construct a reader that finds the package declaration at the beginning of the file. If there isn't one, you don't need to worry about it. Do I need to say you can store package names in a HashSet to avoid duplicate package declarations?
The ICompilationUnit has a findPrimaryType method:
IType primaryType = unit.findPrimaryType();
and IType has getFullyQualifiedName():
String name = primaryType.getFullyQualifiedName();
I have an object profileModel in my profile package and my profile.scala.html file have following code
#(model: ProfileModel)
when I compiles, it is giving an error recursive value model needs type
But when I moved this class to models with my application.conf as
ebean.default="models.*"
it works.
My guess is scala compiler automatically adds models.* to class path at the time of compilation
Is there a way to make this work without moving the class back to models package ?
I am using play 2.2.1 built with Scala 2.10.2
If I understand you right, if your ProfileModel exists in profile package correct declaration in the view should be:
#(myProfile: profile.ProfileModel)
And 'yes', Play imports automatically all models and controllers (and also other well known types), but if you want to use any type in custom package (or ie. imported lib) you need to use full qualified path to it.
I tried to search for the solution, but what I found I don't know how to apply in this situation. Please help me correct my code.
package Exercise;
public class Ex11_11 {
public static void main(String[] args) {
A a = new A(3);
}
}
class A extends B { // type A is already defined, A has a red underline
public A (int t) {
System.out.println("A's constructor is invoked");
}
}
class B { // type B is already defined, B has a red underline
public B () {
System.out.println("B's constructor is invoked");
}
}
Eclipse sometimes gets confused. If you choose Clean from the Project menu, it might fix these errors.
Well, the first thing to check is obviously whether or not you have another class called A in your file or in the same package.
I had the same problem. My computer was restarted remotely by I.T, and Eclipse did not shut down gracefully. I noticed there was an extra java file in my project that I didn't add. Deleted it, and now the error is gone.
In Project-> Clean, select "Clean projects selected below", select my project(s) and check "Start a build immediately" with "Build only selected projects".
Then problem will resolve.
Check if all your class files are saved. I've had this problem a few times: i define a class in a class file then move it in it's own one. Java gets confised, because it reads from the old version of the original file. Once you save it with the missing class definition in it and define the class in the new file all should be ok.
In your project you might have test directory with the same package structure and the same class name (for example copied without changing class name to *Test).
If none of the above solutions worked for you then it possible that Build Path is messed up. When you add a src to the build path make sure the src is not in the exclusion list. Place *(wild card) in the inclusion list and nothing in the exclusion list.
Make sure
Project | Build Automatically
is checked.
The main reason for this is that somewhere in same package you have already defined a class with name A.
which causes type A is already defined error.
check if there is any subclass or inner class named A
Have you added another project to the build path?
I had the same issue on my development environment (Eclipse).
My Maven application consumed other applications. On Eclipse, those projects were just added to the build path. One of them had the same package structure and class filename. Eclipse ends up thinking both the files which are physically different are in the same directory since the package structure and filename are same.
For example, let's say there are two files as below:
/Users/uname/home/proj1/com/app/proj/main/java/util/file1.java
and
/Users/uname/home/proj2/com/app/proj/main/java/util/file1.java
and lets say both have the package name
com.app.define.proj.util
If you add one of the project to the other, Eclipse would consider both the files to be in the same location.
I resolved by creating a JAR file out of the consumed application, adding it to the build path and removing the Eclipse project from build path.
rename the class name A to Aa or something and try to run.
Given a Java source file named as TestMainFunction.java
1.) As most of us would know, a Java file name must be the class name which contains the main function
See the below simple code (in a single file named as mentioned above) which executes perfectly and prints ClassOne.
public class TestMainFunction {}
class ClassOne {
public static void main(String[] a) {
System.out.println("ClassOne");
}
}
2.) When there is more than one class with a main function in a single file, Eclipse prompts the user to choose the class to run.
See the below simple code (single file named as mentioned above) which executes perfectly and prints the class name as we have chosen from the Eclipse promt.
public class TestMainFunction {
public static void main(String[] a) {
System.out.println("TestMainFunction");
}
}
class ClassOne {
public static void main(String[] a) {
System.out.println("ClassOne");
}
}
class ClassTwo {
public static void main(String[] a) {
System.out.println("ClassTwo");
}
}
All the above will work as I mentioned. It will create separate .class file for every class. The same behavior applies even when using inner classes.
But what exactly is happening here? How does Eclipse know which class to launch when multiple classes are present in one source file? Can any one explain it? Explaining this would be greatly appreciated.
As most of you would know, a Java file name must be the class name
which contains the main function
This is incorrect, and I believe the source of your confusion. A Java source file is only allowed to have one public class, and it must have the same name (minus the extension) as it's containing file. A given Java source file though, may contain as many non-public class files as desired, with the only constraint being that their names are valid. Note that you can have a class with the same name as its containing source file (minus the extension) that is not public! Also note that it's generally considered bad practice to have multiple top-level (non-nested) classes in a single Java source file.
The second assumption you may have is that only one class in a source file is allowed to have a main function. This is simply untrue. You can add a main function to every single one of your class files - the only one that matters is the one you specify to the JVM when your application is being launched.
So given your scenario - a source file with multiple class files (one of them public), where each class has a main method, the following applies:
When you invoke the Run command in Eclipse on this file, Eclipse will detect that there is more than one eligible class to be run, and will prompt you to select one of those class. It will then build a 'Run Profile' for the selected class, that launches just that class. You can actually see the profile Eclipse builds via the Run->Debug Configurations menu.
When compiling this source file externally, it will generate multiple .class files (not just one). The classes had no relation to each other save being in the same source file, and you would explicitly select the .class you want to launch in the JVM.
i.e:
java TestMainFunction
java ClassOne
java ClassTwo