Java: Classes

 Hello and Welcome to Java Blog #4, Java: Classes. This post will introduce classes in Java. This blog will not actually show code of a class, but instead, will just explain how they work in a few, short paragraphs. 


All Java programs will need a class or multiple classes. These classes have instances, which are known as objects. You can think of instances, in a way, as basically occurrences of the class. Every object has state, and behavior. State comes in the form of instance fields, and behavior comes in the form of methods, which will be explained in detail soon. 


First are instances, which as mentioned before, are basically objects, which are based on Java classes. An example of this would be Cat being an instance of the "Pet" Class. As you can probably tell, Cat is basically one occurrence, or a usage, of the "Pet" Class. Moving on, every instance has its own set of variables. Only this instance, or occurrence, has access to this set of variables, and they are only used within that instance, not outside. This set of variables are called the "Instance Field," and they are declared within the scope of the instance. 

How do you set the values for the variables in an instance field? This is where methods, or specifically, constructor methods come in use. 

Constructor methods are located inside a class, and they are used to create the instances (once again, occurrences) of the class. This constructor method is named after the class. The constructor method will create the instance, and it will assign the values of the variables in the instance field. Any variables that are declared within the method cannot be accessed and used outside of the method. 

Another important part of Constructor Methods are the parameters. The parameters are variables that are passed into the method, when the method is called, or used. Basically, when you use a method to complete a task, depending on what task it is, you may need some values from outside the method to be passed in. The parameters are basically the method's version of these variables. You give the values to the method when you call it, and the method uses the values you passed in to provide an output for you. 




These are the basics of Java Classes. All of these parts of the class will definitely make more sense when seen is actual coded form. Another post will be released later with example code of basic Java Classes, and explanations of these. There are also other things within these which have to do with the actual code itself, and how it works, which will also be explained.


Thank you for reading Java: Classes. Please leave any comments and questions in the comments section!


Comments