How to create a java class?

Asked

Viewed 12,786 times

5

I would like to know how to create a class in the java, how to use this class in the main program and how is the variable created in this class.

4 answers

6


Initially it is called the main method of the main class (program start), but no instance of the class (object) is created just by doing this.

To create an instance of a class, it is necessary to call the constructor of this class (if there is no one, the compiler will create a constructor without default parameters).

After instantiation it is possible to assign values to object attributes, or else pass them as parameters to the constructor and assign them within the constructor.

In this assignment one must be cautious, because depending on the class of the object being used (in this example the main class), a compilation error will occur if there is an attempt to violate the rules of visibility.

Attribute modifiers, constructors and methods are: protected, package (also called default, which is the absence of modifier), private and public.

The only difference of protected for package (no modifier) is that protected allows subclasses (heirs classes) outside the package to have access.

More details on this question from Soen

Obs: In Java 8, the keyword "default" is a valid modifier for interface methods, and in such a context has no relation to package visibility (default, no modifier).

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

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

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

Class counts with its methods and attributes:

class Conta {
   double saldo;
   String dono;

   void saca(double quantidade) {
     double novoSaldo = this.saldo - quantidade; 
     this.saldo = novoSaldo;
   }
 }

Complementing the subject of modifiers: To ensure greater security and greater encapsulation (among other features) it is necessary to restrict access to variables (usually using access modifiers protected and private) disabling direct access to the attribute (check the access level of each modifier), to provide access is used Access methods get and set:

private double x; 

public double getX() { 
      return x; 
} 

public void setX(double x) { 
    this.x = x; 
}

So for example it is always possible to validate the values to be assigned.

  • works as structin c++ but contains embedded method

  • It has other features that differentiate OO from java with C++/C structs, but it is possible to store pointers to functions within structs.

  • I didn’t understand this placement: "Main Class (because it has the main method), it is called the class constructor, passing the attributes (by default there is no attribute in the default constructor that is created automatically) " The program can have several classes with main methods, these can be executed via the "java" command on the command line. I think it would be interesting to review this explanation.

  • but when it is necessary to run the project as a whole you should keep a single class with main so much that when you try to run in netbeans for example and displayed a pop-up of choice of main classes.

  • You are confusing attributes with parameters. You are also confusing the main method with constructors. It is not true that protected visibility is standard. Your explanation about assigning values in relation to visibility has become confusing, disconnected and meaningless. The balance field does not exist. In addition, you are encouraging and teaching a bad programming practice to beginners without warning about it with direct access to the fields of one class from another, violating the encapsulation. I really like you as a user here at Sopt and I don’t like to downvote, but sorry, -1.

  • @Victorstafusa Where am I confusing attributes with parameters? and main method with constructors? so that I concerte understand better.

  • "Main class (because it has the main method), it is called the constructor of the class" - This is not very clear, but may imply that the constructor of the main class is called, which is not true. Or else that the main method will necessarily call a constructor, which is also not true. Finally, clarify the text at this point. / "is called the class constructor, passing the attributes (by default there is no attribute in the default constructor that is created automatically)" - Here would be parameters and not attributes.

  • @Victorstafusa I will make my text clearer, but there is no wrong information? (went to look for the differences between protected and default and add) it was not my intention that the text gets confused.

  • Well, actually the default is not a visibility modifier, but the absence of a visibility modifier. And to make matters worse, in Java 8, the keyword "default" is a valid modifier for interface methods, and in such a context has no relation to the default visibility. I know I must seem to be very annoying about all this, but it’s just that beginners in the java language tend to confuse these concepts easily, so it’s important that the text is very accurate. And the text of the first paragraph remains confused.

  • @Victorstafusa edited my answer.

  • I also edited the text to clarify upon what you had done, and removed the downvote. I just didn’t understand this part: "In this assignment one must have some caution, because depending on the location of the object that is editing properties (in this example the main class) of another object this operation will not be performed."

Show 7 more comments

5

Classes that can be called as main for Java-SE applications are classes that serve as the input/execution point of their publication, these classes are those that have the public and static method main, this method expects to receive a array of Strings that represents the arguments offered when the class was called with the Java command from the command line.

Even if you use an IDE to run your application, the IDE will call this method stating the parameters that can be passed through the execution parameterization screen.

In the body of the method main you can reference static variables of your class, instantiate the class itself through one of its constructors, and then reference their variables if they are visible, which will depend on their scope. You can also instantiate other classes, manipulate the visible variables and call your visible methods according to the scope.

@Rodolfo, from my point of view your question is very broad and may involve various knowledge concerning the construction of classes and small programs in java.

4

class NomeDaClasse {

      // Atributo
      public int atributo;

      // Método construtor
      public NomeDaClasse() {
      }

      // Metodo
      public void metodo() {

      }
}

To create a class instance:

NomeDaClasse objeto = new NomeDaClasse();
  • Remembering that public attributes are almost always a bad programming practice. And also that constructors are not methods.

2

class AlgumaCoisa 
{
   /* Alguma variável qualquer */
   bool ClasseLegal = true;

   int Arg1 = 0; //primeiro argumento
   int Arg2 = 0; //segundo argumento

   /* O método construtor deve ser o nome da classe */
   public AlgumaCoisa(int Argumento1, int Argumento2) //Pode remover os argumentos se quiser
   { Arg1 = Argumento1;
     Arg2 = Argumento2; }

   /* Propriedade somente leitura qualquer */
   public readonly int CodigoDaClasse()
   { return 20; }

   public int SomaDeles() { return Arg1 + Arg2; }
   public int MultDeles() { return Arg1 * Arg2; }
   public int DivsDeles() { return Arg1 / Arg2; }
   public int SubtDeles() { return Arg1 - Arg2; }
}

to declare it use:

AlgumaCoisa nomeAqui = new AlgumaCoisa(ValorDoArgumento1, ValorDoArgumento2)

Here’s an example with this class:

AlgumaCoisa nomeAqui = new AlgumaCoisa(10, 10)
int Soma          = nomeAqui.SomaDeles(); // 20
int Multiplicação = nomeAqui.MultDeles(); // 100
int Divisão       = nomeAqui.DivsDeles(); // 1
int Subtração     = nomeAqui.SubtDeles(); // 0
  • readonly is not a java modifier. Your code does not follow the conventions of the Java language, and it is important to follow them because this is a question for beginners who would be learning about this kind of thing. Constructors are not methods, and this is important because it is a false information that is always being repeated around and in this topic it tends to be absorbed by beginners in language. Also, your comment "You can remove arguments if you like" will only tend to confuse beginners in the language. I hate to downvote, but sorry, -1.

  • 1

    Yes, I’m not good at Java, I consider Java a language comparable to C#, because then I have a notion that Java accepts the syntax of C#, I accept his vote and he is welcome, because everyone has the right to have an opinion, I will try to improve my experience in Java, It’s a new world for me.

Browser other questions tagged

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