I cannot compile a Java class which instance is another Java class

Asked

Viewed 99 times

0

Here’s the thing, I have two classes: Account.java and Program1.java the idea is for the Program1 class to create an Account instance and use it within the program but I’m not able to compile the Program1 class by the prompt (I’m not using IDE).

Java account.:

package generico;

class Conta {
    int numero;
    String titular;
    double saldo;
}

Program1.java:

package generico;

class Programa1{
    public static void main(String args[]){
        Conta minhaConta;
        minhaConta = new Conta();

        minhaConta.titular = "Duke";
        minhaConta.saldo = 1000.0;

        System.out.println("Saldo atual: " + minhaConta.saldo)
    }
}

The following error appears when I try to compile Program1.java:

Programa1.java:5: error: cannot find symbol
                Conta minhaConta;
                ^
  symbol:   class Conta
  location: class Programa1
Programa1.java:6: error: cannot find symbol
                minhaConta = new Conta();
                                 ^
  symbol:   class Conta
  location: class Programa1
2 errors
error: compilation failed
  • Calde the "public" in the class names?

  • Remove the package q works.

1 answer

6

If you are running both classes from the same operating system folder through the command prompt (Windows) or console (linux), you do not need to inform package. Remove package generico that the code works perfectly.

inserir a descrição da imagem aqui

  • I use Windows 10. I see that in your gif it is working right the way I wanted, but here, even with the changes did not work. I am seeing that my problem is further down by the following: When I am going to run a java class I cannot do using "java Minhaclasse" because it gives the error: Error: Could not find or load main class Minhaclasse Caused by: java.lang.Classnotfoundexception: Minhaclasse. I have to do "java Minhaclasse.java"

  • @Juviosa if remove what I said in the reply and run straight from the directory as shows the gif, not from the error. If so, it is not a java problem, but rather how you set up the classpath on your computer, which is a very different problem from the question

  • I removed what you said. And yes, I think the error is in the classpath. Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.