Java packages - refer to a class from another package

In (default package) I have a class called "Bird" that has a "dialog" method.

I can create class Class1 in one package, for example:

public class Class1
{
    public static void main(String[] args) 
    {
        Bird b = new Bird("Alexander",true,5);
        b.dialog("tweet!");
    }
}

It really works, and I really see it tweet!in the console.

My question is: what do I need to add to the code if it Class1is in the package Fundamental(whereas the class Birdis in the "default package")? I get an error: "Bird type not recognized" in this case. Probably I should specify the package somehow.

Side questions: 1. What is a classpath and how do you change it? I have seen this term vaguely used in the context of several discussions related to packages, but none of them contain the clear examples that I just gave. 2. I have seen many times packages called xxx.bla.zzz - is that standard? I usually use a common name (not three separated). I understand that the package replaces Java with namespaces in other languages. If you have several solutions worth mentioning, I would appreciate it. Thank!

+5
source share
3 answers

You should never use the default package, this is not a good practice, and you cannot import classes from the default package. Always declare your package structure.

In the class Birdon the first line add:

package animals;

1.java

package foo;

import animals.Bird;

, Bird Class1 "" "foo"

+10

JLS ( 7.5. http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5) ( )

(Β§7.4.2) , , () , (b ) . , Β§7.5.1, Β§7.5.2, Β§7.5.3 Β§7.5.4 ( ) .

+3

, , , NetBeans, . . NetBeans . : : , , , . ,

newPackage;

import , :

import newPackage.SecondClass;

In fact, you can use ctr + spaceBar code completion to make sure the package is clearly visible.

I expect it to be simple enough. check this screenshot

+2
source

All Articles