Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Packages - refer to a class from a different package

Tags:

java

package

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

I can create a class called Class1 within the same package, like this:

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

This actually works and I actually get to see tweet! in the console.

My question is: what do I need to add in the code if Class1 is located in the package Fundamental (whereas the class Bird is located in the "default package")? I get an error: "Bird type not recognised" in this case. I should probably indicate 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 package-related discussions, but none with clear examples as I just gave. 2. I have seen many times packages called xxx.bla.zzz - is this a standard? I only usually use a common name (not three separated by .) I understand a package is Java's replacement for namespaces in other languages. If there are several solutions solutions worth mentioning, I'd appreciate. Thank you!

like image 811
Sam Avatar asked Jan 29 '13 21:01

Sam


1 Answers

You should never use the default package, it is not a good practice and you can't import classes from the default package. Always declare your package structure.

In the class Bird in the first line add:

package animals;

In the first line of your Class1.java write your package name

package foo;

import animals.Bird;

Note that for this to work the class Bird and the class Class1 should be respectively in the folder "animals" and the folder "foo"

like image 88
fmsf Avatar answered Oct 07 '22 14:10

fmsf