I jsut learned that
A class may be declared with the
modifier public, in which case that
class is visible to all classes
everywhere. If a class has no modifier
(the default, also known as
package-private), it is visible only
within its own package.
This is a clear statement. But this information interfere with my understanding of importing of packages (which easily can be wrong). I thought that importing a package I make classes from the imported package visible to the importing class.
So, how does it work? Are public classes visible to all classes everywhere under condition that the package containing the public class is imported? Or there is not such a condition? What about the package-private classes? They are invisible no mater if the containing package was imported or not?
ADDED:
It seems to me that I got 2 answers which are marked as good (up-voted) and which contradict eachother.
Importing a class doesn't change its visibility in any way. Importing a class to another class is more or less just a way to make your source code readable so you don't have to put in fully qualified class all the time. For example this class
import java.util.*;
class ImportTests {
private Collection collection;
}
compiles to the same code that this class would
class ImportTests {
private java.util.Collection collection;
}
The import statement in the first class doesn't change the visibility of Collection or any other class inside the java.util package it just makes it so the ImportTests class can reference Collection without the fully qualified name.
You do not need to import a path or a class to make it visible.
To make classes or paths visible, you have to specify at classpath declaration during compilation or execution.
"import" directive ("using" directive in C#) merely helps us to be lazy.
If you have classes
why.does.the.sun.go.on.Shining.java,
rather.be.ahammer.thana.Nail.java,
you could always refer them with their full paths without importing them:
public java.util.Hashtable<rather.be.ahammer.thana.Nail> bornFree(
java.lang.String shiningKey,
why.does.the.sun.go.on.Shining shiningPath){
rather.be.ahammer.thana.Nail nailed =
new rather.be.ahammer.thana.Nail(shiningPath);
java.util.Hashtable<rather.be.ahammer.thana.Nail> nailedHash =
new java.util.Hashtable<rather.be.ahammer.thana.Nail>();
nailedHash.put(shiningKey, nailed);
return nailedHash;
}
However, laziness being the virtue of creativity, I would rather do
import java.util.Hashtable;
import why.does.the.sun.go.on.Shining.java;
import rather.be.ahammer.thana.Nail.java;
public Hashtable<Nail> bornFree(
String shiningKey,
Shining shiningPath){
Nail nailed =
new Nail(shiningPath);
HashTable<Nail> nailedHash =
new Hashtable<Nail>();
nailedHash.put(shiningKey, nailed);
return nailedHash;
}
Which, you probably have already realised.
1 - The question would then be,
if there are two classes of the same name but different namespace, which would be used by the compiler?
import java.util.Date;
import java.sql.Date;
The compiler would complain with error message - conflicting classes for Date
and you would not be able to compile successfully.
So you have to import one of them and use the other with its full path.
In C# we could import
using Dayhawk = hello.day.Hawk;
using Nitehawk = hello.nite.Hawk;
So that we could do,
DayHawk dhawk = new DayHawk(new NiteHawk());
However, either as always, the java authoritarians are either to shy/proud to allow themselves to allow java immitate Microsoft or that Microsoft has a patent on such form of import.
2 - The second question would be,
if we had a class
atlantic.salmon.are.trouts.String.java
Then you did an import
import atlantic.salmon.are.trouts.String;
And when you declare
String salmon = new String();
which String would be used? java.lang.String or atlantic.salmon.are.trouts.String?
The compiler would pick and obey the import statement and use atlantic.salmon.are.trouts.String.
3 - the third issue,
private, protected, public visibility modifiers and default visibility are not to be confused with the import directive at all. Nothing to do except being in the same language.
private references are visible only
within the same file.
protected references are visible only
within the same namespace packages or
by an extension class.
public references are visible to all.
Undeclared, i.e. default, references
are visible only within the same
namespace packages.
Import directive does not change these behaviours at all.
In conclusion,
The import directive is merely for
the continuance of the virtue of
laziness.
The import directive is not for the
purpose of making classes visible or
changing the visibility of their
contents.
The classpath argument is for making
classes visible to the whole project.
Noting else can change the behaviour
of visibility modifiers in a Java
compilation.
I have two packages A and C. A has a class named Random in it. My code here compiles fine, and the random is from A and not from java.util. The java.util import gives me a warning in eclipse that the import is unused.
package C;
import A.Random;
import java.util.*;
public class C
{
public static void main(String[] args)
{
Random b = new Random();
}
}
Here is another example of the hiding of classes.
package C;
import java.util.*;
public class C
{
public static void main(String[] args)
{
Random b = new Random();
System.out.println(b.nextDouble());
}
}
Here is my Random class.
package C;
import java.util.Scanner;
public class Random
{
private static final long serialVersionUID = 2632389638401709212L;
Scanner s;
public Random()
{
super();
s = new Scanner(System.in);
}
public double nextDouble()
{
System.out.println("Enter your own random number");
return Double.parseDouble(s.nextLine());
}
}
When I run the C main method I get...
Enter your own random number
1
1.0
If you want to use class A from class B, and class B is not in the same package with class A, you must import class B, even if the class B is public.
If public classes didn't need to be imported, there could be no way of declaring two classes with the same name.
Related
Given this code:
package my.pkg;
import com.google.common.util.concurrent.Service;
class Test implements Service {
public static void main(String... a) {
System.out.println(Listener.class);
}
// method implementations omitted for brevity
}
And given there's one Listener class in my.pkg, and one as an inner class in the Service class I'm importing.
I would expect the package local class to 'win' here, since I'm not referring to Service.Listener.class or explicitly importing the inner class. Apparently, IntelliJ expects the same thing, since if I explicitly add import my.pkg.Listener;, it is automatically removed as being redundant. However, when compiling and running this code (Gradle 2.14.1 and openjdk 1.8.0_91, if that matters), it's very clear the inner class is winning.
How do I get this code to use the class in my.pkg? Explicitly adding the import doesn't work, since my IDE removes it. I'd also prefer not to use full class names (my.pkg.Listener) everywhere in the class.
I'm new to Java and I've got a package for interfaces. Each interface has a number of imports for the types used in the interface declarations.
// MyInterface.java...
package a.b.c.interfaces;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
public interface MyInterface() { ...
Then I've got a package with models, and inside of it, I'm attempting to create a class that implements MyInterface().
// MyImplementation.java...
package a.b.c.models;
public class MyImplementation implements MyInterface {...
I have two questions:
Does MyInterface() need to be imported into
MyImplementation()? If not, does it then need to be linked
manually during compilation?
If MyInterface() is imported, is
it also necessary to import the types the interface requires, or
does the import of MyInterface.java take care of this?
Imports in Java is basically a way of telling the compiler that when you write MyInterface you really mean a.b.c.interfaces.MyInterface. It is definitely possible to write Java code without using imports but it is extremely verbose and looks messy.
You need to import any type that you want to use that is not in the same package as the class you're writing or in java.lang so since MyInterface is in a.b.c.interfaces and MyImplementation in a.b.c.model you need to import it.
You do need to import the classes that MyInterface is using if you're writing their type anywhere in your code - and since you're implementing the interface you will need to write their types in your method declarations. There is no way of using the same imports as another class in Java.
Here is an example of usage of types where we don't need to import them:
UsesBigInteger.java:
import java.math.BigInteger;
public class UsesBigInteger {
public BigInteger get() {
return BigInteger.TEN;
}
}
Main.java
public class Main {
public static void Main(String[] args) {
UsesBigInteger use = new UsesBigInteger();
System.out.println(use.get());
}
}
The reason we don't have to import java.math.BigInteger here is that we never actually write BigInteger anywhere so we don't need to tell the compiler what we mean by that - we just pass the return value from UsesBigInteger.get() along and the compiler already knows that that is a java.math.BigInteger.
If we want to keep a reference to the BigInteger we need to import it though:
Main.java
import java.math.BigInteger;
public class Main {
public static void Main(String[] args) {
UsesBigInteger use = new UsesBigInteger();
BigInteger it = use.get();
System.out.println(it);
}
}
Ans for your first question, you have to import the interface and on class you have to implement your interface.
As for your second question, you just need to import MyInterface. The JVM will take care of the rest.
I strongly suggest you to go threw the oops concepts as its too basic question.
And also use any IDE like Eclipse.
A.java
package a;
class A {
void f1()
{
System.out.println("hi");
}
}
B.java
In same folder as of A.java and class files are generated in the same folder.
package b;
class B
{
new A().f1();
}
I am new to package concept. My question here is even though they are not in the same package how can B create the object of A?
If you use public class declaration it goes to public access level. Public classes can be accessed by different packages by using import a.A; or providing the complete class name new a.A().f1().
B will import (or can use fully qualified name) the class A from other package if it has to use it. importing enables the classes in other packages to see the classes from a different package. But this can be further find-tuned by using scoping.
If both are in the same folder and not using any packages explicitly then they both are in the default package. And you no need to explicitly import the classes while using them if they are in the same package.
You should know access modifiers in java. If your class is public ,it can be accessed anywhere simply by importing it.
Please go through below link for better understanding
http://javapapers.com/core-java/access-modifiers-in-java-explain/
There is something called import in Java which you can import into current package and access methods or members as long as they are public(visible across package) or protected (visible to sub-classes)
What is the best way to implement a system to establish program-wide constants? I have a program that spans several files and I want to have a class that stores constants so that they are available for all the other files.
I tried something like this:
in Constants.java
public final class Constants{
private Constants(){}
public static final String EX = "mas";
}
and in test.java
import Constants.*;
public class test{
public static void main( String[]args){
System.out.println( EX );
}
}
but I get the following error
test.java:1: error: cannot find symbol
import static Constants.*;
^
symbol: class Constants
Constants.java and test.java are in the same dir.
You can not import from the default package. See Java Language Specification
Put the class in a package.
You can't import classes without a package (also called the default package)
If these two classes are in the same package, you do not need to import.
Remove the import statement for Constants class
In your test class, use the following line: Constants.EX to get the value of EX.
You'll need to preface your reference to Constants in the import with the full package name.
For example, if Constants and test are in the package "com.mystuff", you'll need to import as follows:
import static com.mystuff.Constants.*;
Alternatively, since your classes are in the same package you don't really need the import at all - just qualify EX with the Constants class, e.g. Constants.EX instead of just EX.
Any public static final variable will be accessible anywhere without creating an instance of an object. In your case you can access the EX variable with:
Constants.EX;
In general with good object-oriented design the constants which you include in a class should be specific to that object type. For example if you have a Window object its constant might be "aspectRatio" or "height" but it would be inappropriate to have "nameOfUser" in a Window class as a constant. So sometimes making a "universal" Constants class will inherently make you lose sight of which variables truly belong in different classes when following object-oriented ideals.
In java parent package class accessible from child packge class? please explain me any one?
example
package A.A1.A2 contains class sub
package A contains class sup
Is there anyway to access sup from sub?
pls explain.
i tried import it won't work
Example:
before the program Directory Structure is
package1 contains package1.java --> package2 --> package3 contains PCheck.java
//package1.java
package package1;
public class package1{
public static void main(String[] args) {
}
}
class phelo{
phelo(){
int a;
System.out.println("hai fun freom package 1");
}
}
//PCheck.java;
package package1.package2.package3;
import package1.*; //to import package1.java
public class PCheck {
public static void main(String[] args) {
phelo obj=new phelo();
}
}
class helo{
helo(){
int a;
System.out.println("hai fun from package 3");
}
}
output:
compile time error:package package1.package2.package3 doesnot exist;
for import class from different directory we use import statements but here we need access parent package from subpackage.i tried import it won't work pls explain with an example.
Java does not recognize the notion of a subpackage1. As far as Java is concerned packages a and a.b and a.b.c are unrelated. They are just names.
So, if you want to access a.b.SomeClass from a.b.c.SomeOtherClass, you must either use a fully qualified class name, or add an import to SomeOtherClass
1 - From Java 9 onwards you can use modules to implement abstraction boundaries that are larger than a single package. This doesn't address this question which is about package-private access, but it could be viewed as an alternative to package-private.
As for your example that doesn't compile, I think we need a proper MCVE to understand that. My guess is that you have gotten the file organization for your source tree wrong ...
It is also possible that the problem is that the visibility of the class you are trying to import is wrong (package private), but that wouldn't cause the compiler to say that the package doesn't exist, like you said it does.
In java parent package class
accessible from child packge class?
please explain me any one?
Not the way you're thinking. The directories are hierarchical, but the packages are just distinguishing names.
If a child needs a parent package, or any other outside its hierarchy, it simply needs to import it.
That's why import foo.* doesn't give you access to all sub-package names - packages aren't hierarchical the way directories are.
All answers seem to miss OP's point on package class as everyone seem to suggest importing the class as a workaround.
The answer is: package-level classes (i.e., without explicit access level modifier), are visible ONLY for the EXACT same package.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If a class has no modifier (the default, also known as package-private), it is visible only within its own package
This effectively means that neither parent/child/external packages can view the class.
In object of a.b.c.SomeOtherClass:
List<String> tmp=new ArrayList<String>(Arrays.asList(this.getClass().getPackage().getName().split("\\.")));
tmp.remove(tmp.size()-1);
String parent_package_name=tmp.toString().replace(", ", ".").replaceAll("[\\[\\]]", "");
Class cls=Class.forName(parent_package_name+".SomeClass");
Simply import it:
import A.sup;
Yes I have encountered the same error whenever I tried to access a class in the same package of the source file or the parent package of the source file it is generating a compiled time error , so by trial and error method I came to the conclusion that the packages are not built in a way to support main methods in the classes and they are not built in a way to support importing their parent packages or child packages
default class can be only used within package except subpackage