DEV Community

Cover image for Exploring the Basics of Objects and Methods in Java
Isah Jacob
Isah Jacob

Posted on • Edited on

Exploring the Basics of Objects and Methods in Java

When you're first learning to program in Java, one of the most important concepts to learn and understand is objects and methods. Objects and methods form the foundation of object-oriented programming (OOP) in Java, which is a powerful programming paradigm that allows you to write more organized, efficient, and reusable code. In this article, I'll explain the fundamentals of Java objects and methods and help you understand how they work.

Before continuing with this article, it is important that readers have a good understanding of basics of Java. If you need to brush up on your basic programming skills in Java, I recommend reading the basics of Java here.

What are objects in Java?

Java is an object-oriented programming (OOP) language.
What this means is that every class in Java is supposed to be a blueprint for an object with the same name. Think of an object as an instance of a class, which is a blueprint for creating objects.
The syntax to declare a new object

<object_type> <object_name>;
Enter fullscreen mode Exit fullscreen mode
String myCar;
Enter fullscreen mode Exit fullscreen mode

To initialize an object, you have to create it using the keyword new:

<object_name> = new <class_name>();
Enter fullscreen mode Exit fullscreen mode
myCar = new Car();
Enter fullscreen mode Exit fullscreen mode

You can declare and initialize the same type like this:

<object_type> <object_name> = new <class_name>();
Enter fullscreen mode Exit fullscreen mode
String Car = new Car();
Enter fullscreen mode Exit fullscreen mode

An object in Java is also known as an instance, and the process of creating an object is called instantiation.

Objects can store values in the form of attributes and execute instructions in the form of methods. The idea of objects is that they each have a different value for a common characteristic.

To declare an instance attribute, create a variable outside the main method (example below). This allows Java to recognize the syntax, and every object you create will have a copy of that variable that can store a different value in each object.

To access the value of an attribute, refer to the object's name, then type a dot and the attribute's name. You may modify this value just as you do with a usual variable, but remember that you will be changing the value of that attribute for the object you are referring to.

The word private below means that the attribute can only be accessed by this class.

Here's an example of a simple class with attributes in Java.

public class Car {
    private String make;
    private String model;
    private int year;
}
Enter fullscreen mode Exit fullscreen mode

From the above class definition, "Car defines a Car object, which has three attributes (information): make, model, and year. These attributes or pieces of information represent the make, model, and year of the car, respectively.

To create an object of this class, you use the new keyword and the class constructor, like this:

Car myCar = new Car();
Enter fullscreen mode Exit fullscreen mode

This creates a new Car object and assigns it to the variable myCar. You can then set the attributes of the object like this:

myCar.make = "Toyota Camry";
myCar.model = "Civic";
myCar.year = 2022;
Enter fullscreen mode Exit fullscreen mode

This sets the make, model, and year attributes of the myCar object.

Let's see a simple Java program.

public class Car
{   
     private String model;
     private String make;
     private int year;
  public static void main(String[] args)   
{     
    Car myCar = new Car();
    myCar.model = "Civic";      
    myCar.make = "Toyota Camry";      
    myCar.year = 2022; 
//creating a different object with different attributes      
    Car ourCar = new Car();      
    ourCar.model = "City";      
    ourCar.make = "Honda";      
    ourCar.year = 2023;      
//accessing values of attributes of objects      
   System.out.println("My car's model is " + 
   myCar.model);      
   System.out.println("My car's make is " + 
   myCar.make);      
   System.out.println("My car's year is " + myCar.year);
   System.out.println();      
   System.out.println("Our car's model is " + 
   ourCar.model);      
   System.out.println("Our car's model is " + 
   ourCar.make);      
   System.out.println("Our car's model is " + ourCar.year);   
  }
}
Enter fullscreen mode Exit fullscreen mode
Output:::
My car's model is a Civic.
My car's make is a Toyota Camry.
My car's year is 2022. 

Our car's model is City.
Our car's make is Honda.
Our car's year is 2023.
Enter fullscreen mode Exit fullscreen mode

Take a look at the code above; notice any repetitiveness? How is the process of creating an object and assigning values to its variables carried out? There's a solution for that. It's constructors.

What is a constructor in Java?

Constructors tell Java how to create an object when you already know the values you want to assign to its attributes.

A constructor is a special method that is used to initialize objects in a class. It is called automatically when an object of the class is created, and it is responsible for setting initial values for the object's attributes. The constructor has the same name as the class and is defined within the class.

The main purpose of the constructor is to ensure that all objects of a class are created with a valid initial state. This helps to prevent errors and ensures that the object is ready to be used in the program.

The syntax is

public <class_name> ( <parameters> ) { 
values assignation 
}
Enter fullscreen mode Exit fullscreen mode

Never place them inside the main method.
The keyword public allows any class to access it, be it a class or an attribute.

Now, let's look at a simple example in Java to understand how constructors work:

public class Car{
    private String model; 
    private String make;  
    private String year;

    // Constructor
    public Car(String model, String make, int year) {
        this.mode = model;
        this.make = make;
        this.year = year;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the example above, we have defined a class called Car with three attributes: model, make, and year. We have also defined a constructor that takes three parameters: model, make, and year.

Within the constructor, we use the this keyword to refer to the current object being created and set the initial values for the model, make, and year attributes.

Now, when we create a new object of the Car class, the constructor is called automatically and sets the initial values for the object's attributes.

Here's an example:

// Create a new Car object in the main method.
public static void main(String[] args)
{   
    Car ourFamilyCar = new Car("City", "Honda", 2023);   
    Car daddyCar = new Car("Civic", "Toyota Camry", 2022);
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have created two new Car objects called "ourFamilyCar" and "daddyCar," which passed in the values "City", "Honda" and 2023 for ourFamilyCar, and "Civic", "Toyota Camry" and 2022 for daddyCar as the model, make, and year attributes, respectively.

Constructors are an essential part of object-oriented programming, as they ensure that objects are created with valid initial states and are ready to be used in the program.

What Are Methods in Java?

Methods are blocks of code that perform a specific task. In Java, methods are defined within classes, and they can be called on objects of that class.

Another useful thing you can do with objects is to make them execute certain instructions. A method is essentially a piece of code that is only executed when the name of the method is called (or invoked).

Apart from executing a block of code, methods have the property of returning (or giving you) values. And just as with any other variable in Java, you must specify what type of thing it is.
The syntax is

public <return_type> <name_of_method> (arguments) { 
code to execute when it is called 
}
Enter fullscreen mode Exit fullscreen mode

The arguments are certain values that may be required to carry out the code's logic. Arguments are not necessary, but beware: even if you don't ask for arguments, you must put them in parentheses () because they're part of every method's syntax.

Void Method in Java

In case you do not want to get a value from the method, the return type should be set as void. Like in the code here.

public void start() {
    System.out.println("The car is starting.");
}
Enter fullscreen mode Exit fullscreen mode

When this method is called, start() which is the method name simply prints a message to the console.

To invoke this method on a Car class object, use the dot notation, as shown in the main method below.

public static void main(String[] args){   
Car myCar = new Car("Civic", "Toyota Camry", 2022);   
myCar.start(); //apply method to myCar object 
}
Enter fullscreen mode Exit fullscreen mode

When the code above runs it calls the start() method on the myCar object, and the message "The car is starting." is printed to the console.

Output:::
The car is starting.
Enter fullscreen mode Exit fullscreen mode

Parameters and return values in methods

Methods can also take parameters and return values. Parameters are inputs to the method, and return values are outputs from the method.

It is commonplace to code a method that does some calculation and then gives you (returns you) that value. In that case, you must know beforehand what type of data you expect to get and place it in the <return type> part of the method's definition instead of void. Here's an example of a method with parameters and a return value:

public int accelerate(int speed) {
    int newSpeed = speed + 10;
    return newSpeed;
}
Enter fullscreen mode Exit fullscreen mode

This method, called accelerate(), takes an int parameter called speed and returns an int value. The method adds 10 to the speed parameter and returns the result.
To call this method on an object of the Car class, you pass in a value for the speed parameter and store the return value in a variable, like this:

public static void main(String[] args)
{   
   Car myCar = new Car("Civic", "Toyota Camry", 2022);   
   myCar.start();
   System.out.println("current speed: " + 
   myCar.accelerate(50));
}
Enter fullscreen mode Exit fullscreen mode
Output:::
current speed: 60
Enter fullscreen mode Exit fullscreen mode

This calls the accelerate() method on the myCar object, passing in a value of 50 for the speed parameter. The return value of the method (60) is stored in the newSpeed variable.

Wrapping-up

Objects and methods are fundamental concepts in Java and OOP. Understanding how to create and use objects and methods is essential for writing effective and efficient Java code. By following the examples provided in this article, you should be well on your way.

Your feedback is highly appreciated.
you can follow me on twitter and linkedIn

Top comments (2)

Collapse
 
tijan_io profile image
Tijani Ayomide

Very informative and well written... Thank you for sharing

Collapse
 
jacobisah profile image
Isah Jacob

Thank you so much. I appreciate this.