简体   繁体   English

无法在同一个包中实例化公共类

[英]Can't instantiate public class in the same package

So I made this java file A.java, 所以我制作了这个java文件A.java,

package alphabet;


public class A{
   private  String private_A;
   String _A;
   protected String protected_A;
   public String public_A;

   public A(){
      private_A="Private A";
      _A="Package Private A";
      protected_A="Protected A";
      public_A="Public A";
  }
  public static void main(String[] args) {

  }
}

and another class in the same package, 和同一个包中的另一个类,

package alphabet;

import alphabet.A;

public class B{
    void methodB1(){
    }
    public static void main(String[] args) {
        A AinB = new A();

    }
}

When I compile B I can't instantiate A . 当我编译B我无法实例化A Why is that? 这是为什么? A is a public class, and B belongs to the same package? A是公共类, B属于同一个包吗? Shouldn't B be able to make an instance of A ? 不应该B能够做出A的实例吗?

This pretty noobish, but thanks. 这很漂亮,但谢谢。

EDIT: Got these errors, 编辑:有这些错误,

*@*:~/rand$ javac B.java 
B.java:3: error: cannot find symbol
import alphabet.A;
               ^
  symbol:   class A
  location: package alphabet
B.java:9: error: cannot find symbol
                A AinB = new A();
                ^
  symbol:   class A
  location: class B
B.java:9: error: cannot find symbol
                A AinB = new A();
                             ^
  symbol:   class A
  location: class B
3 errors

EDIT : Removed the import statement still getting these errors 编辑 :删除导入语句仍然收到这些错误

B.java:9: error: cannot find symbol
                A AinB = new A();
                ^
  symbol:   class A
  location: class B
B.java:9: error: cannot find symbol
                A AinB = new A();
                             ^
  symbol:   class A
  location: class B
2 errors

由于您的类是包字母表,因此您需要将它们放在名为alphabet的子目录中,然后使用以下命令行从其父目录运行javac:

javac alphabet/B.java

Problem is you are compiling it wrong. 问题是你编译错了。 Since you are using package, while compiling you need to be outside the package. 由于您使用的是包,因此在编译时您需要在包外。

So instead of javac B.java 所以不是javac B.java

Make a folder/directory named same as package name ie alphabet and move the java files to it. 创建一个与包名称相同的文件夹/目录,即alphabet ,并将java文件移动到它。

Use javac alphabet/B.java 使用javac alphabet/B.java

删除B类中的import语句。您不需要从同一个包中导入。

You have 2 main methods, you should only have 1 which is for starting the program off, try creating a A object in be or whatever class you want to run first: 你有2个主要方法,你应该只有1个用于启动程序,尝试创建一个A对象或者你想先运行的类:

package alphabet;


public class A{
 private  String private_A;
String _A;
protected String protected_A;
public String public_A;

public A(){
  private_A="Private A";
  _A="Package Private A";
  protected_A="Protected A";
  public_A="Public A";
  }
  public static void main(String[] args) {
    B bclass = new B();
    bclass.yourmethod();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM