Knowing how to define a class in Java is essential for anyone who wants to start object-oriented programming. In this post I will demonstrate in a practical way how to define a class in Java.
Step 1:
After already defined in your project the place where you will allocate your classes just click with the right mouse button on the chosen package, then on the option "New/Novo" and then on the option "Class/Classe" as indicated below .
Step 2:
After following the steps above, a screen will be displayed where you must fill in some information regarding your class.
As indicated on the side, the fields for package, Source Folder and others will already be filled in. Here at first you just need to fill in the name you want for your class and then click on "Finish/Finish".
When you have deepened your knowledge about Java classes, you can use this screen to do some work, such as automatically generating some methods.
A .java file will then be created with the following structure:
package Classes;
public class ExampleClass {
}
From this in theory you already have a class created, but of course, so far it has no use, as we saw in the previous post a class can have attributes and methods, in this post we will discuss how the attributes of a class can be defined in Java. So let's get to the attributes.
Step 3:
To define the attributes of this class the steps are very simple, for that however you should already have clear in your mind if these will be public or private attributes.
Remembering that public attributes can be accessed and modified internally and externally to this class, while private attributes can only be modified internally in your class through some method, for example.
Defining a public attribute:
package Classes;
public class ExampleClass {
String name = "Academico Tech";
int age = 20;
}
In the code snippet above we defined two attributes, name and age. In this case these attributes already come with pre-established values, but it is possible, however, later on, to make these values dynamic.
Step 4:
To show on the screen or use any of this information, it will be necessary to instantiate an object of this class so that this is possible. As shown below:
package Classes;
public class ExampleClass{
public String name = "Academico Tech";
public int age = 20;
public static void main(String[] args) {
ExampleClass a = new ExampleClass();
System.out.println(a.name);
}
}
In the code snippet above, within the main constructor method we create an instance of our class ("ExampleClass a = new ExampleClass();") and then display the "name" attribute on the screen.
Having this structure established, you have your class ready and functional, of course, this is a class in its most basic form, in future posts we will discuss how to define methods that, in addition to giving life to classes, open up a huge range of options to work with. with Java classes.
Comentários