Do I have to use "package" term in every class? - java

Firstly, I'm trying to learn Java with Java, A Beginner's Guide, 4th Edition. I use Ubuntu as my OS and Netbeans as my IDE. I need to create a project to create a class when using Netbeans.
Here is my hello world app.
class First{
public static void main(String args[])
{
System.out.println("Hello!");
}
}
But this returns a lot of errors. When I put package first; line to top line of my Java class it runs. But, the book isn't using package term. Is this a rule of Netbeans, or what I need to know about this?

You never need to put a class in a package. However, it is almost always a good idea. This is something that Netbeans aggressively tries to encourage you to do.
For small projects, using the default package (that is, a file without a package statement) is OK. However, once your project grows and starts adding external libraries, bad things can happen. What if someone else decided to use the default package and happened to have an identically-named class? Now, since you're both in the same package, collisions can occur!
Your file structure should also reflect your package. That is, a file in package com.myurl.helloworld should be located in a folder called com/myurl/helloworld. This is for the same reasons as above.
Also, and you probably haven't gotten here in your studies, you cannot import classes from the default package, or use the package-private visibility modifier in a default package class.

That's because the author of Java, A Beginner's Guide, 4th Edition most likely used the "default package". This way, you don't have to include any package. A package is a namespace declaration.
What the heck is a namespace declaration!?
A namespace declaration is simply a package which is made to organize your classes. For an instance, if you're going to have multiple classes for, let's say your GUI, and multiple classes for algorithms, blending them together is always a bit confusing. Sorting them in different packages, however is a superior solution.
There is also a naming convention which you should follow if other people are going to look at your code. Packages should be named after a top-level domain. I tend to create SourceForge projects and then I end up with something like this:
net.sourceforge.softwarename.security, net.sourceforge.softwarename.gui, etc...
Also note that you should never use upper case when naming your package. More info here.
You're going to encounter lots of situations like these when learning to programming. They're all a part of the game. You'll just have to figure out a bit by yourself.
The best I can do for you is to recommend Eclipse. Also, when learning Java, I would suggest that you do not use an IDE at ALL! That's because you'll learn to code independently. It's up to you, though.

No you don't need to put in a package into your class UNLESS you are going to import it to another class that will be in it's own file. This is where protected type variables come in when you don't want to make them priviate but only want the subclasses (or child classes) access to them. You are also missing your public statement for your class so it should look like
public class First{
public static void main(String[] args){
System.out.println("Hello!");
}
}

Package represents a directory that contains related group of classes and interfaces.
A package is a namespace that organizes a set of related classes and
interfaces. Conceptually you can think of packages as being similar to
different folders on your computer. You might keep HTML pages in one
folder, images in another, and scripts or applications in yet another.
Because software written in the Java programming language can be
composed of hundreds or thousands of individual classes, it makes
sense to keep things organized by placing related classes and
interfaces into packages.
Below you can find some good discussions regarding java packages:
Java packages com and org
Are there best practices for (Java) package organisation?
Java com.* package namespace

Related

Hierarchy of Java Packages

I was trying to understand the general hierarhcy of Java packages.
If you consult this Oracle page, it seems that there are 3 main packages:
java, javax and org.
All packages, in Java platform 7, start with one of these three.
Are these ones part of a bigger package?
I'd love to see a complete tree, but the one offered by Oracle is very confusing, because it's too detailed.
Another thing I did not undestand is why packages like "java.awt" and "java.awt.color", or "java.lang" and "java.lang.annotation", are put by Oracle on the same level.
I did read online that if you import a "parent-package", you don't import any classes form the "child-packages", and that makes sense. However, it's hard to think that there isn't a relation between java.awt and java.awt.color; It seems intuitive that the least is contained in the fromer.
So, given my current understanding, I would draw a tree that look like this:
No, there is no "bigger" package. The structure evolved over time, with different ideas and marketing influencing the naming.
You do not import packages in java, just classes. So before Java9, it does not really matter much even in which package a class resides except for the package-protected visibility scope (which is not used that much), and the lack of need to import classes from the same package.
Often classes from a subpackage are used by classes in a parent package, but not the other way round. But there is no strict rule about this.

Effective Java Item 13 and TDD

I just googled "Joshua Bloch TDD"... not much came up, which is a huge shame because I'd really like to know what he's got to say on the matter.
Item 13 (I'm looking at the 2nd edition) is entitled "Minimize the accessibility of classes and members". After a couple of pages he says:
To facilitate testing, you may be tempted to make a class, interface
or member* more accessible. ... It is acceptable to make a private
member of a public class package-private in order to test it, but it
is not acceptable to raise the accessibility any higher than that...
Luckily, it isn't necessary either, as tests can be made to run as
part of the package being tested, thus gaining access to its
package-private elements.
* by "members" he means "fields, methods, nested classes and nested interfaces".
As a TDD newb, but gradually finding my feet, I am aware that the current consensus seems to be not to include testing classes with the app code packages, nor even to have a matching structure under src\test and src\main: mostly TDD experts readily seem to structure their testing directories in other ways (e.g. you have one directory called "unittests" another called "functionaltests" and another called "e2etests").
Specifically, I have followed the TDD development of the auction app in "Growing Object Oriented Software Guided by Tests". The author there has no qualms about adding hundreds of public methods. Furthermore, after one chapter I looked at the downloaded "structure so far" and he had completely changed the testing directory structure to divide things into categories of test...
Is there any seasoned TDD hand out there who has, at least in the past, found this to be a source of dilemma? If so, how have you resolved it?
As a practical example, I'm cutting my teeth on TDD techniques by developing a Lucene index app: it indexes documents and then lets you query them. At the current time all the app classes are in the same package. The only method which actually needs to be public is main in one class. And yet, of course, I have many, many public methods: they could all be package-private were it not for the fact that I am using TDD.
PS no tag for "method-visibility" so I chose "class-visibility"
later
It appears that I may have been led down a rather unfortunate path by the approach taken in "Growing Object-Oriented...", where the over-use of public methods was presumably used just because it's a demonstration of the technique. Ha.
If you want to split your categories of tests, does anyone ever use this sort of approach:
\src\unit_tests\java\core\MainTest.java
but also, for example:
\src\func_tests\java\core\MainTest.javaand
\src\e2e_tests\java\core\MainTest.java?
as tests can be made to run as part of the package being tested
This does not mean that you have to put your tests in the same directory as main classes, they just have to be in the same package which can very well be separate directory.
Assume you have a package com.acme.foo. So your directory structure may be:
src
main
java
com
acme
foo
MainClass
test
java
com
acme
foo
MainClassTest
MainClassTest is in the same package as MainClass so it has access to package-private stuff. But these are separate directories, so your resulting JAR will not contain MainClassTest.
I am not sure how this works in Gradle, as I am using Maven, but I imagine the concepts there are similar. Therefore I will explain it with Maven in mind.
The typical setup in a Maven project looks like this:
On the root level of the projects there is src and target. Into the target folder everything goes that is created during the build process. This means that src contains the sources of our actual project. Under src there are two other directories: main and test. Simply put into main goes everything that will end up in the productive code, that will be delivered. The test directory contains the test code for the main tree.
Therefore it is usual that the same package hierarchy from the src/main/java directory is also present in src/test/java and therefore for a test class with the same package definition will have access to all members of the producive class which resides in the main branch.

Java files on the same folder and on the same package

At least on my machine when I put 2 Java class files on the same folder, without making them part of the same package, they already see one another, so from one file I can call a public class from the other file and vice-versa.
Questions:
Is this the general case or a coincidence that may not work on every platform?
If this is not a coincidence, I am guessing the purpose of packages is to allow you to organize your class files and make they share stuff, even if they are spread across different folders and paths. Is this correct or I am missing something?
If no package name is specified, the classes in the file go into a special unnamed package. And this is the same case for all files with no explicit package specification. Hence, they all fall into the special unnamed package, and exhibit the behavior that you are seeing.
You might want to go through this for a better understanding.
If they're in the same directory then they're in the same package, or are you copying .class files around after they've been written by the compiler?
Packages are a way of organising classes into a namespace. There are plenty of reasons to do this, the best bet is to start with the tutorial.
I sure it is general case, but it is bad approach.
You are right, but more general reason to use package is to separate namespaces, for example, you have to create Car class, but there are many people who want to use this classname, thats why you have to use package, for example: com.yourcompany.yourproject. In such case you can use your Car class from your package without implicitly defining package and you also can use other Car classes in such manner: new com.google.general.Car();
In the java rules, it is recommend to use domain name right-to-left for providing unique package name.

Why do Java sources have so many folders inside each other?

Every time I look at some Java source code, I find myself surfing in a folder that has folder that has folder that has folder in it etc. Why does Java require so many nested folders, which have nothing else in them except the new subfolder?
For example:
https://github.com/halfninja/android-dragcontrol3d/tree/master/src/uk/co/halfninja/android
That's probably not the worst example, but there are two folders "uk" and "co" that just don't make sense. I see this in Java sources only!
And for example minicraft: http://www.ludumdare.com/compo/ludum-dare-22/?action=preview&uid=398
import com.mojang.ld22.gfx.Font;
import com.mojang.ld22.gfx.Screen;
import com.mojang.ld22.gfx.SpriteSheet;
Why not just write:
import gfx.Font;
import gfx.Screen;
import gfx.SpriteSheet;
That's so much cleaner.
(I have never programmed in Java.)
These are there to prevent conflicts with other jars. Having something like the company url in the package name makes it likely to be unique enough to not conflict with someone else's package and classes.
Your example is a good one, since it seems pretty reasonable to imagine two people thinking of using "gfx" as a package name and with classes like Font or Sprite. Now, if you wanted to use both of them, how could you since the package and class name would be the name?
Your way is cleaner, but it assumes nobody else in the world is ever going to create a package called gfx, which is a pretty weak assumption. By prepending your reversed domain name, you create a unique namespace that avoids collisions.
This fits perfectly with the "culture of sharing" that pervades Java programming, in which applications typically combine large libraries from many sources.
In Java, the convention is to name your packages (which correspond to the folder structure containing your code) with information identifying your organization (typically including a TLD and the company name) and project (which might add a few more sections).
Being more specific like this also reduces the likelihood of namespaces accidentally colliding with eachother.
It's merely an organizational technique for preventing namespace conflicts. Nothing more or less. Java package names match the underlying directory structure, so any organizational pattern at the package level will be reflected there. It's typical for teams to start their package names with their organization's name and wax specific. This is simply convention, but it's ingrained and should be followed absent a very good reason.
It's all about Namespaces. With 'Namespaces', you can create 2 classes with the same name, located in different packages/folders. This Namespace logic can also be used for creating 'Access Privileges', etc etc. Below are some links:
1) Namespace
2) Java Package
3) Java Package Naming Conventions
EDIT: Let us assume that you are creating a new project and are using 2 open source frameworks from companies/organizations - comA and comB. Also, let us assume that comA and comB have created a class in their projects with the same classname. Now, with the Java package naming conventions, we have com.comA.SomeClass and com.comB.SomeClass. You can import and use both the classes in your class, without having a conflict. This is just a simple example. There are other uses from this naming convention.
If you want to share code with everyone else, but use generic names without conflict. its considered good practice to include you domain name (backwards)
Everyone write a package called gfx.Font you wouldn't be able to use more than one version in the same application.
You might feel your code will not be shared with the world (or even should not be shared) In which case, a shorted package structure may be simpler.
If you use an IDE, it does a good job of hiding long package structures so you don't need to worry about it.
This is due to recommended packaging structure. In large projects, so many packages/libraries are used and in order not to put source files into same folder with another library, programmers put their source codes into unique folders. As websites are unique, it is a convention to use packaging structure that looks like folder structure of websites.
Java does not require anything: you can just put all your classes in the default package and surf away. But for serious projects that kind of organization is not only wise, it's mandatory. The com.mojang.ld22 part is just a convention:
com = either this or org, java/javax for official packages
mojang = second part is company name
ld22 = third part is application name

Encapsulating functions in a second .java file?

I've been messing with Android for a couple of weeks, i found many tutorials to follow, but i didnt find anywhere some "Style rules" to make the code looks better.
I would like to know if its possible (im sure that it is, but dont know how to make it xD) to use more .java files to organize the functions. I mean, right now, i have myApp.java where i coded all my application, but is starting to grow so much, so i would like to separate some functions into another .java file.
As i told before, im almost sure that this is possible, but i dont know how to link that second file so, can anybody help me?
Thank you in advance :)
If I understand you correctly you haven't really learned how to use classes in your application? My suggestion is to do a Google search 'Java for beginners' and look for references to Classes and objects.
You normally don't "link" a file in Java as opposed to some other programming languages. In Java you have java files that compile to class files and use them by creating instances of them like so.
MyClass instance = new MyClass();
Where MyClass is defined in a file called MyClass.java (and located in the same package/folder as your main application). If you are unsure about package another Google search can illustrate how to use them.
If you are using Eclipse, it can help you with this. You can create a class and use it by creating a new instance of it in your main application.
You're talking about separation of concerns - you should examine your application design and have classes where the functionality is broken down into logical units per class.
If you're talking about static methods, where you wish to call some functionality which doesn't rely on the state of an object, then perhaps a utility class could be appropriate.
The java.lang.Math is an example, where all the methods on the (final) class are static. Ideally you would just import the methods you'd want to use in your code using the import static keywords.

Categories

Resources