Should a java package have only one public class? - java

I tired creating a package with one public class and one with multiple public classes and then import them through another package and both times the program worked. I understand the difference, in the first i can only use the methods of the one public class, but that class can use other classes in its package, and when more classes are public i can directly access all those classes through the alien package.
Now when we import java.util.Scanner, and we import java.util.ArrayList isn't this the same package? When we import our package with one public class it only shows the one public. That means that java.util has multiple public classes, or?
Also what does that java. mean, does it make the difference between my package and java library packages?

Yes, a package can have multiple public classes.
Creating a new package for every public class would be extremely cumbersome and provide no overview at all.
java. are just the standard libraries that come with the JDK/JRE.
Packages are really just like folders on your system. You can have multiple files in a folder without a problem.
Typically packages are structured in a way that they combine related classes to make it easier for the developer. If you want to have no packages at all, or you want a new package for every class: it doesn't matter. You'll be your own worst enemy, but it is surely possible.

import java.util.ArrayList;
means: let me use the class ArrayList, which is in the package java.util, by only typing ArrayList and not java.util.ArrayList.
java.util is the name of the package, nothing else. It's where the Java developers chose to store the ArrayList class. It's not different from any other package name, except you're not allowed to use the java package for your own classes, because it's reserved for standard Java classes.
import java.util.*;
means: let me use all the classes of the package java.util (ArrayList, LinkedList, Collection, etc.) by typing their simple name (ArrayList, LinkedList, Collection, etc.) instead of their fully qualified name (java.util.ArrayList, java.util.LinkedList, java.util.Collection, etc.)
All these classes are public (as documented in their javadoc). If they weren't public, you wouldn't be able to use them in your own classes.

Related

Why do you need to import java.util.* to use Arrays.toString()

The Arrays.toString() would not work without import java.util.* for some reason. Here is a simple java code that deletes an element from an array by the length of the string that the user inputs.
import java.util.*;
public class conjunction {
public static String func(String x[], int input) {
String temp[] = new String[x.length - 1];
String temp2[] = new String[x.length - 1];
for (int c = 0; c < x.length; c++) {
if (x[c].length() == input & c + 1 < x.length) {
temp2[c] = x[c + 1];
x[c + 1] = x[c];
x[c] = temp2[c];
} else if (x[c].length() != input) {
temp[c] = x[c];
}
}
return Arrays.toString(temp);
}
}
It says it cannot resolve symbol Arrays.
That's because the Arrays class lives in package java.util, so you either need to import it explicitly (with import java.util.Arrays;) or you import everything from that package (with the wildcard import java.util.*;)
More generally, everything in Java lives in a package and needs to be imported, with the exception of the java.lang package, where classes like String live, which is imported by default.
An import is never required in Java, and in fact it does not exist at the byte-code level. Your code will work if you remove the import statement and change your return to
return java.util.Arrays.toString(temp);
An import reduces the typing required at development time (it is a programmer convenience).
import java.util.Arrays; also works
using import statement is vary beginner OOP concept in JAVA.. according to your question toString(temp) is a static method of Arrays class. And the Arrays class belongs to package java.util, so using that static method you need to import java.util.Arrays. point to be noted every java class by default import java.lang.*
here i am sharing some thought about package.
Every thing in JAVA belong to package. Package are used in Java, in-order to avoid name conflicts and to control access of class, interface and enumeration etc. A package can be defined as a group of similar types of classes, interface, enumeration or sub-package. Using package it becomes easier to locate the related classes and it also provides a good structure for projects with hundreds of classes and other files.
Mainly Java project support two Types of Packages: Built-in and User defined
Using import keyword
import keyword is used to import built-in and user-defined packages into your java source file so that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to any class that is present in a different package:
Using fully qualified name (But this is not a good practice.): Like return java.util.Arrays.toString(temp);This is generally used when two packages have classes with same names. For example: java.util and java.sql packages contain Date class.
To import only the class/classes you want to use : Like import java.util.Arrays;. then only the class with name Arrays in the package with name util will be available for use.
To import all the classes from a particular package: Like import java.util.*. it make all the classes and interfaces of this package (util package) will be accessible but the classes and interface inside the subpackages will not be available for use.
Points to remember
When a package name is not specified, the classes are defined into the default package and the package itself is given no name.
Java.lang.* package in Java: Provides classes that are fundamental to the design of the Java programming language.
toString() is a method inside Arrays class(static) and this class is in the package java.util.The source file for this class is in package named util which is in a package named java.
Also we can use package qualifiers instead of import.
The import statement is not always required.Class reference can be made with explicit qualification with "." operator.
eg java.util.ArrayList<String> str //fully qualified
There is one situation where qualification in necessary- when two classes have same name but are in different packages.
egjava.util.Timer and java.swing.Timer
Here the name Timer is ambiguous and can't be used without qualification.

A wildcard is said to import all classes in a package. "It doesn't import child packages, fields, or methods." What does this mean?

In the Sybex book, OCA Oracle Certified Associate Java SE 8 Programmer I - Study Guide, page 10 of Chapter 1 states the following:
The * is a wildcard that matches all classes in the package. Every
class in the java.util package is available to this program when Java
compiles it. It doesn’t import child packages, fields, or methods; it
imports only classes. (Okay, it’s only classes for now, but there’s a
special type of import called the “static import” that imports other
types. You’ll learn more about that in Chapter 4.)
It was my naive understanding that since a class contains members (fields and methods), it is implied that those are imported, as well. However, according to the author of this book, it appears that the situation is more caveated.
If you are importing a class, and you don't have access to the members of that class, then what is the point of importing that class?
what is the point of importing that class?
Imagine that you do not import classes inside java.util. If you want to create a Map you type:
java.util.Map<String, Integer> myMap = new java.util.HashMap<>();
If you import the class in that package like import java.util.*;:
Map<String, Integer> myMap = new HashMap<>();
If you are importing a class, and you don't have access to the members
of that class
Imports do nothing with access, they are all about readability and convenience. You don't have to type that much and the second declaration is much more readable, but you can use the same methods of myMap in both cases.
The static import that the book mentions (from the doc):
The static import declaration is analogous to the normal import
declaration. Where the normal import declaration imports classes from
packages, allowing them to be used without package qualification, the
static import declaration imports static members from classes,
allowing them to be used without class qualification.
A good example for static import is the usage of Mockito in unit tests. Without any imports you can verify some behavior like:
org.mockito.Mockito.verify(mock, org.mockito.Mockito.never()).someMethod();
If you use normal import import org.mockito.Mockito;:
Mockito.verify(mock, Mockito.never()).someMethod();
and with static import import static org.mockito.Mockito.*; you can type
verify(mock, never()).someMethod();
Here the verify and never static methods can be used even without specifying their class (Mockito).
If you are importing a class, and you don't have access to the members of that class, then what is the point of importing that class?
Suppose you have a package com.ebony.maw.utils, and that package has a class MyUtilities, and the class has a static method findFizgigs(). If you say
import com.ebony.maw.utils.*;
you can now say
MyUtilities.findFizgigs("thingy-002");
instead of having to say
com.ebony.maw.utils.MyUtilities.findFizgigs("thingy-002");
But you still can't say
findFizgigs("thingy-002");
without the class name. That's what they mean by importing the class, but not importing the method. It just means you can use the class name without having to supply a package name prefix. But you can still use the method--you just have to supply the class name as a prefix.

I don't understand what does java.util. mean [duplicate]

This question already has answers here:
Meaning of the import statement in a Java file
(5 answers)
Closed 6 years ago.
What does java.util.*; do? Why do we include it at the beginning of our files?
The statement java.util.*; imports all of the java.util package members so that you don't have to use a package member's fully qualified name. According to the JavaDocs here the package java.util
Contains the collections framework, legacy collection classes, event
model, date and time facilities, internationalization, and
miscellaneous utility classes (a string tokenizer, a random-number
generator, and a bit array)
Although this approach can seem more convenient and is sometimes appropriate you shouldn't always be including an import java.util.*; statement at the beginning of all of your files unless you are using a substantial amount of the members contained in the java.util package. Only include the members that you use like so:
import java.util.ArrayList;
import java.util.LinkedList;
By doing so it helps make you more familiar with each package member that you're using instead of blindly importing the whole package. The most important reason is that by using the wildcard character(*) you have a greater chance of coming across name ambiguities which can lead to errors.
import java.awt.*;
import java.util.*;
In the above code example, the class List becomes ambiguous because both packages have a List class.
Think of it like a library of methods that you now have access to. You are basically importing more functionality into your project
When you do
import java.util.*
you now have the ability to do things like create arrays, manipulate dates and so on... (https://docs.oracle.com/javase/7/docs/api/java/util/package-summary.html)
The .* means you are importing all of the util functions like java.util.Arrays or java.util.Date...

Does the star import include subpackages in Java?

When you declare an import like this:
import com.microsoft.azure.storage.*;
Does that include everything in its subpackages too? For example, does it include this?
import com.microsoft.azure.storage.blob.*
If not, why not? (Edit: the "why" question is basically off topic. ignoring that bit when considering a correct answer.)
No it does not. It only imports everything in the package (i.e. the directory itself). Sub-directories are considered to be different packages, so you would need to:
import com.microsoft.azure.storage.*
import com.microsoft.azure.storage.blob.*
As to why the language designers chose to go this route, one can only guess, but the system that they decided to go with does allow for a more fine-grained approach.
yes you can import all the classes from an import but it does not make it possible to import multiple packages with similar names. For example import java.util*; does not also import java.util.prefs or .jar you have to import these all separately. I don't know if that answers your question, and to the why I am not really sure it just makes sense to do it this way. If you were to import similar packages that had the same static variables, but you only need two or three of the packages then you would get errors or code that does not run properly.
There's a name for these - type import on demand.
A type-import-on-demand declaration allows all accessible types of a named package or type to be imported as needed.
They're only also importing the package itself, and not any subpackages, as clarified by the example, emphasis mine:
import java.util.*;
causes the simple names of all public types declared in the package java.util to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places in the compilation unit where that type declaration is not shadowed (§6.4.1) or obscured (§6.4.2).
does that include everything in / subdirectories too? including
something like this?
* stands for all the compilation units inside the package com.microsoft.azure.storage where sub packages are actually not compilation units and thus not fetched when you write myPack.*. Compilation unit includes class, interface, enum etc.

Method that imports things

Is it possible to make a method in java that can import things? If so how is it done? If you are wondering why I am asking this, it is because I am making a library in java to make your code smaller.
This is not possible in Java. You have to import the resources (classes, interfaces, enums, static imports, etc.) in each file. At most, you can use less code by importing all the public classes and interfaces that belong to a package by using * wildcard. Example:
//Importing all classes and interfaces declared ad java.util package
import java.util.*;

Categories

Resources