简体   繁体   中英

Can't instantiate public class in the same package

So I made this java file 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 . Why is that? A is a public class, and B belongs to the same package? Shouldn't B be able to make an instance of 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

Make a folder/directory named same as package name ie alphabet and move the java files to it.

Use 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:

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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