I have started learning Java and I tried to play with import and inheritance in netbeans IDE.
In netbeans I have created a project and two folders 'food' and 'food1'.
food has Fruit.java in it and food1 has Apple.java.
here's the code which is working fine.
Fruit.java
package food;
public abstract class Fruit{
}
Apple.java
package food1;
import food.Fruit;
class Apple extends Fruit{
}
Problem:
1. If i'm not declaring packages(package food and package food1) , it's not working. But i have already put them in the folders manually.
2. If i'm removing the import statement, it's not working. But the class fruit has been declared public.
Your Problem descriptions are correct - means, it works as expected:
If i'm not declaring packages(package food and package food1) , it's not working
Yes, the directory structure must be consistent with the package names. If your directory structure looks like
src
+--food
| +--Fruit.java
+--food1
+--Apple.java
then Fruit.java needs to have the package food statement and Apple.java needs to have the package food1 statement.
If i'm removing the import statement, it's not working. But the class fruit has been declared public.
Yes, if you want to use a class from a different package you must import it (or use a fully qualified class name which includes the package name, like ... extends food.Fruit - the usual approach is to import, though). Declaring the class public is not sufficient - it just defines the class can be used from outside the package, but you still need to import it.
See also
https://docs.oracle.com/javase/tutorial/java/package
http://www.studytonight.com/java/package-in-java.php
Related
Let's say I have this Java class:
package com.version1;
class Sample
{ ... }
And in another Sample class, I want to import the Sample class from com.version1 package:
package com.version2; // Now it's a different package
import com.version1.Sample; // From another package
public class Sample
{...}
Please note: I need to import a class with same name as the current class, not 2 classes with same name.
So the question: Importing two classes with same name. How to handle? is not similar.
You simply can't have two classes referenced by the same short name. So the solution is actually the same one as in the case of importing two classes with the same name:
You'll have to reference the other class by its fully qualified class name and your local one by its short name. You could even use the FQCN for both, if that helps readability in your case.
Simple question but even though googled it a lot I could not find the answer.
Is it possible to import a class outside a package?
Let's say I have 2 folders A and B with a .java file in each, is it possible by using the clause import to import the class contained in A? import A.Aclass ? or it's mandatory using package syntax whenever there is the keyword import?
Yes it is possible to import the class with the import statement. For better understanding let's assume that you have three folders foldera, folderb and folderc where foldera contains a .java file named "ClassA.java", folderb contains another .java file named "ClassB.java" and folderc contains a .java file named "ClassC.java". Now, if you want to uses the member data and operations of "ClassA.java" in "ClassC.java" you can use the import statement as shown below:
import foldera.ClassA
If you want to use the member data & operations of "ClassB.java" in "ClassC.java" it is also possible with the import statement
import folderb.ClassB
As per the java source file declaration rule, if the class is a part of a package, the package statement must be the first line in the source code file, before any import statements that may be present. In this example, the first line of "ClassC.java" source file must be package folderc since it is located in folderc. Similarly, the first line of "ClassA.java" source file must be package foldera, and the first line of "ClassB.java" source file must be package folderb.
Hope now you are clear with the concept!
Thank you...
Well, if the class is defined to have a package a; then you need to import the class with the package name. If you have two packages which contain a class with the same name, then in your class which needs to invoke each of them, you will need to use a fully-qualified name. For example:
import a.Foo;
import b.Foo;
public class Bar
{
public static void main(String[] args)
{
a.Foo aFoo = new a.Foo();
b.Foo bFoo = new b.Foo();
}
}
Alternatively, if you have two packages with classes of the same name, you can simply skip importing them, but rather -- using them by their fully-qualified names (FQN-s).
If the class does not have a package ...;, then simply import it as:
import Foo;
However, if you have two packages (from different libraries) which contain classes with identical FQN-s, then the first one on the classpath will be picked.
Please, bear in mind that the convention for naming packages is to use lowercase letters and for classes -- the name should start with an upper case letter for each word in the class' name.
Yes it is possible.
If you have the following:
Package: PackA
Class: ClasA
Do:
import PackA.ClassA; //Import the class
OR
import PackA.*; //Import all the classes within the package
yes it is possible just import the package
syntax
import pck.ClassA or import pck.*
Yes, you have to use package syntax.
importing all class inside folder A.
import com.pack.A.*;
importing specific class inside folder A.
import com.pack.ClassName;
Consider the following simple example of code:
public class TestStaticImport {
static enum Branches {
APPLE,
IBM
}
public static void doSomething(Branches branch) {
if (branch == APPLE) {
System.out.println("Apple");
}
}
}
If we will try to compile this code, we will get the error message:
java: cannot find symbol
symbol: variable APPLE
location: class TestStaticImport
This could be solved by introducing static import of this enum:
import static ... TestStaticImport.Branches.*
But in this moment incomprehensible things (for me) begin:
this solution works fine, everything is well compiled, until class TestStaticImport will be moved into empty root package, i.e. there isn't any
package blablabla; in the top of this java file;
Code line: import static TestStaticImport.Branches.*; is highlighted as valid code in my Intellij IDEA (name of IDE doesn't matter, just for information), but when I try to compile such code following error appears:
java: package TestStaticImport does not exist
So, there are actually two questions:
1) Main question: why is it impossible to import static from empty directory?
2) What is another way (if it exists) for allowing in code references to enum's fields using just their names (i.e. APPLE instead of Branches.APPLE), except static import?
P.S. Please, don't tell me, that empty packages is ugly style and so on. This question is just theoretical problem.
The Java language specification forbids any imports from the unnamed package:
A type in an unnamed package (§7.4.2) has no canonical name, so the
requirement for a canonical name in every kind of import declaration
implies that (a) types in an unnamed package cannot be imported, and
(b) static members of types in an unnamed package cannot be imported.
As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time
error on any attempt to import a type (or static member thereof) in an
unnamed package.
In ancient times, the Java inventors had to map Java types to files so the compiler could do some real work. They decided to map packages to folders and types to files. That worked pretty well. It especially set the emotional background for newcomers: "I hate you. Don't mess with me." But I digress.
The default package is a problem, though, since it doesn't have a well defined folder. If you have package com, you know that there is a folder com somewhere but what's the name of the folder for the default package?
So the designers decided that import and default package don't mix. In fact, you get an error when you try to import anything that has no package (i.e. import TestStaticImport without the static and * would also fail). See How to import a class from default package
So the problem isn't the static import but that you try to import from the default package.
Like some other corner cases in Java, there is no solution.
see also: In Java- "Static Members of the default package cannot be imported"- Can some one explain this statement?
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)
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