Java Classes



This article is about the use of Classes in Java.

What are Java Classes?

In Java, classes play a larger than usual role. This is apparent since everything in Java occurs within classes. So what is class then?

A class is a template or blueprint that defines the form of an object. It defines the code and data that it will use. Using this “blueprint” or “template” the object is then created. Remember, objects are instances of classes. A class itself is never executed, rather it’s objects are the ones executed. This is also why we call objects the physical representation of classes that exist in the memory.

Another alternate definition for a class, not involving objects. “It is a collection of methods (functions) and attributes (variables)”. Anything belonging to the class, such as methods, are referred to as members of the class.

The terms object and instance are very interchangeable here, so expect to hear both. The best way to describe is that an object is the actual thing made using the blueprint (class) and the instance is a virtual copy of that object.


Classifying Classes

This is an issue that comes up when you’re creating multiple classes. People tend to miss the point of a class. A class is meant to hold information regarding a certain topic or field. For instance, one might create a class called student. You can expect it to have student related variables and methods, like Roll_No, Grade, School etc. Including variables like, Avg rainfall, Stock price, Seasons would ruin the point of having a student class.

Similarly, don’t create a massive class filled with all kinds of different fields and topics. For instance, if you’re creating classes for all the people in a school. Make three classes, one for the students, one for the teachers and one for the staff. This allows for greater organization and readability.


Java Classes Syntax:

Below is the general form a class, complete with two variables and a method.

class class_name {
     // Declaring instance variables
     int var1; 
     int var2;

     // Declaring methods
     type method1(parameters) {
         // Instructions
     }
}

If this your first time approaching classes in Java, you’ll already know about the class with the main() method. The main() method defines the starting point in a Java program. Here, we’ll be creating multiple classes and multiple methods.


Constructors

A constructor is a method in Java that runs automatically when an object of that class is created. For this reason, it’s typically used to initialize variables belonging to a class. You can declare a method as a constructor by giving it the same name as the Class. See further into this article as to how to declare methods.


Defining Classes

We’ll be creating as an example, a class called “Vehicle”. We’ll be creating variables which store relevant information regarding the Vehicle Class.

class Vehicle {
    int passengers;    // number of passengers
    int fuelcapacity;  // Max fuel capacity in liters 
    int mpl;           // Miles covered per liter
}

As you can see, this class doesn’t currently have any methods. For now, it’s just a data class, since it only purpose is to hold data. We’ll be using this class through this page, further building on it.


Creating a Class object

Remember a class itself can never be executed. To actually begin using our class, we need to create a class object first. Objects are also known as the “instance” of a class.

Vehicle car = new Vehicle();

The above code creates an object called car from the class Vehicle. In the next step, we’ll proceed to store data in the variables of the object car.


Storing Data

To store data in the variables of the object car, we need to first access them. We cannot access them directly due to Variables Scopes, hence we need to mention both the object name and the variable name, separated by a dot operator.

Here we’re assigning values to all three of the variable in the object car.

car.passengers = 5;
car.fuelcapacity = 70;
car.mpl = 10;

Creating a method

The specifics behind creating a dealing with methods is a separate beast, and covered in detail in the methods section. We’ll simply go over the basics here.

The Method’s general form, where type is the data type of the return value. (Assuming there is a return value)

type method_name(parameters) {
    // Instructions
}

Below is a method we’re going to create for the Vehicle class.

double maxrange(int capacity, int usage) {
     int range;
     range = capacity / usage;
     return range;
}

Java Classes – Full Example

This example is a combination of all the previous examples and concepts. In here you’ll see the full code of the Vehicle class and it’s objects.

class Vehicle {
	    int passengers;    // number of passengers
	    int fuelcapacity;  // Max fuel capacity in liters 
	    int mpl;           // Miles covered per liter
        
          // Defining maxrange method
	    double maxrange(int capacity, int usage) {
	    	int range;
	        range = capacity / usage;
	        return range;
	   }
}

public class example {			
	public static void main(String[] args) 	{	
	
		Vehicle car = new Vehicle(); // Creating object
		
              // Storing Data
		car.passengers = 5;
		car.fuelcapacity = 70;
		car.mpl = 10;
		
              // Calling function with parameters and printing
		System.out.println(car.maxrange(car.fuelcapacity, car.mpl));		
	}
}

This marks the end of the Java Classes article. Any suggestions or contributions for CodersLegacy are more than welcome. You can ask any relevant questions in the comments section below.

Leave a Reply

Your email address will not be published. Required fields are marked *