Java 包 - 引用来自不同包的类 [英] Java Packages - refer to a class from a different package

查看:91
本文介绍了Java 包 - 引用来自不同包的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在(默认包)中,我有一个名为Bird"的类,它有一个名为dialog"的方法.

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

我可以在同一个包中创建一个名为 Class1 的类,如下所示:

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!");
    }
}

这确实有效,我实际上可以在控制台中看到 tweet!.

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

我的问题是:如果 Class1 位于包 Fundamental 中,我需要在代码中添加什么(而类 Bird位于默认包"中)?在这种情况下,我收到错误消息:无法识别鸟类类型".我可能应该以某种方式指出包裹.

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.

附带问题: 1. 什么是类路径以及如何更改它?我已经在几个与包相关的讨论中看到了这个术语的模糊使用,但没有一个像我刚刚给出的那样有明确的例子.2.我见过很多次叫xxx.bla.zzz的包——这是标准吗?我通常只使用一个通用名称(而不是三个以 . 分隔的名称)我知道包是 Java 替代其他语言中的命名空间.如果有几个解决方案值得一提,我将不胜感激.谢谢!

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!

推荐答案

你不应该使用默认包,这不是一个好的做法,你不能从默认包导入类.始终声明您的包结构.

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.

在类Bird的第一行添加:

package animals;

在 Class1.java 的第一行写上你的包名

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

package foo;

import animals.Bird;

请注意,要使其正常工作,Bird 类和 Class1 类应分别位于文件夹animals"和文件夹foo"

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

这篇关于Java 包 - 引用来自不同包的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆