RastcodeS

Where we take good care of both your front and back-end needs

Great place to take your code to the next level

Checkout my work and get in touch



RastcodeS Logo
Go Back

Java Break - Packages and Imports - Java Core Part - III


Java



Written by Rastko

date - 30/Aug/18 | views - 131

Java Break - Packages and Imports - Java Core Part - III

     Exploring Java packages and importing classes. Wildcards and conflicts explained.

     This is the third article in a series - Java Break, where we explore core Java features. If you want to check out the previous two, here are the links:

Java Break - Class Structure - Java Core Part - I

Java Break - Main Method - Java Core Part - II

 

Java Packages

 

     Java comes with a lot of built-in classes and I do mean a lot. We're talking about thousands, that help us do all kinds of things. On top of that, in your own apps you may have hundreds of classes, and we need a way to organize it all. Packages are coming to the rescue.

Package Structure

 

     Think of classes like the folders in the picture above. As you can see, each can also include packages. These, we call child packages, and they help us further organize our programs.

     There's a specific way to get the classes inside this packages. For the classes in the customers package the address would look something like:

customers.CustomerTracker

 

     On the other hand if we want a class from the marketing child package:

customers.marketing.CampaignManager

 

     We go from broader, then we narrow it down to a child package and finally get the specific class. You can look at it like the mail services delivering a package to your address. First comes the country, then the city and state and finally the street name and the number.

 

Importing Classes

 

     In our daily programming we might want to utilize some pre-made classes in our apps. How would we do that? For example, there's a Date class in the util package, that provides a way to deal with, well dates:

public class NoImport {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.println(date);
   }
}

 

     This code doesn't compile, because Java doesn't know what you're talking about. Let's fix that by adding an import to the top.

import java.util.Date;

public class ProperImport {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.println(date);
   }
}

 

     If you're following along and compile and run this code, you'll see that now we have small little program, that prints the current date and time. We tell Java to first look in the java package, and yes there are other standard packages. Then we go into util and finaly we designate a specific class, in this case the Date class.

 

Wildcards

 

     Now that we know how to import classes, you might be wandering if there's a way to import multiple classes from a package, without writing an import statement for each of them? Of course there is - wildcards to the rescue. For this example, we're going to use another class from the util package - Random. Random class, as the name says, helps us generate random numbers:

import java.util.*;

public class WildCardExample {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.println(date);
      Random random = new Random();
      System.out.println(random.nextInt(100));
   }
}

 

     The * symbol is our wildcard. It tells Java that we want to import all of the util class. We end up having a working program that prints the date and a random number between 0 and 99.

     Very important. The * symbol only imports the classes from the packages it is added to. It will not import any classes from the child packages. To illustrate this, let's take another look at our example from before:

 

Package Structure

     This code only get's the classes from the products package:

import products.*;

 

     On the other hand if you would like to import the classes from the stores package, you'd have to do it like this:

import products.stores.*;

 

Lang Package and redundant imports

 

     About now, you're probably scratching your head a little bit. We have be using the System class all this time without importing it. That's because the Sytem class is located inside the java.lang package, which is imported automatically. There wont be any issue if you specifically do import it, just know that it isn't necessary.

     Similarly, while writing your programs, you amy end up with some other redundant imports:

import java.lang.*;
import java.util.*;
import java.util.Date;

public class RedundantImports {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.println(date);
   }
}

 

     Here we only need one import statement and we can get rid of the other two. First, we don't need the lang import as it is automatically imported. We can also remove either the util.*, or the util.Date import, as in our case they're doing the same thing. This may not seam like a very complicated issue, but we'll come back to it when we start our OCA test - tricky questions series.

 

Name Conflicts

 

     Even though it is considered a bad coding habit, you might end up with multiple classes with the same name. In fact, java built-in packages have a few examples of this. We've already shown the Date class from the util package, but there's another one inside the sql package as well:

import java.util.*;
import java.sql.*;

public class NameConflict {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.println(date);
   }
}

 

This code will not compile, as Java is unsure which class you actually want to use. For an odd reason, you may actually want to do this and there are to ways.

 

Specific Import:

import java.util.Date;
import java.sql.*;

public class NameConflict {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.println(date);
   }
}

 

     Here, we're being specific that we want to use the Date class from the util package and the other Date import is being overridden. This code compiles fine, but it's obvious that the other import, at least in our case has become redundant.

 

Specific Use:

public class NameConflict {
   public static void main(String[] args) {
      java.util.Date date = new java.util.Date();
      System.out.println(date);
      java.sql.Date sqlDate;
   }
}

 

     Yes. you can do this and yes this code compiles. Here, we're telling java, what each of our variables are going to be exactly. Still, try and avoid writing classes with the same name, because this practice may lead to confusion.

 

New Packages

 

Now that we've talked about packages and imports at great length, it's time to use it in our own code. We'll want to use our example from the start as a blueprint:

 

Package Structure

 

     You might be wandering, what's this default folder, you've been skipping over it all along? We'll it's time to tell you that all of our previous examples have had this package, you just haven't seen. It's an unnamed, so called default package, that is actually the root of your app. Each of our classes in these examples was in the default package. That was ok, but it should stay in the examples. It is considered a bad coding practice to put anything inside this package, as it leads to confusion. It's fine when you're learning, but avoid it once you start writing some production code.

     Alright, our task for the day is to create a new folder, that is going to be the root of our project. I'll call mine OnlineShoppingApp. Inside it, create two more folders - customers and products. Inside the products folder add a new file - ProductOrder.java:

package products;

public class ProductOrder {
   int id;
}

 

     As you can see, now that we're dealing with new packages, we need to use the package keyword in order to specifically tell Java, where this class belongs.

 

     Similarly, in the customers folder add a new file - OnlineCustomer.java:

package customers;

import products.ProductOrder;

public class OnlineCustomer {
   String name;
   ProductOrder productOrder;
}

 

     Here, we designate the package and that we want to import the ProductOrder class rom the products package. You're free to play around and add the child packages, the logic should be the same.

     This little program doesn't do anything as we don't have the main method and we haven't covered creating new java objects yet so stay tuned, as this will be the topic of the next Java Break. Se you there!


View Post/Backend
Login to comment

Comments


No Comments yet. Be the first!

Currently working on a Laravel project

Check it out
Java Break - Declare and Initialize Variables - Java Core Part - VI
Java Break - Declare and Initialize Variables - Java Core Part - VI

     Declaring and initializing variable in Java. How to do it properly and avoid mistakes.

     The sixth chapter...

Java


Recents


Popular