Objects in Java

In Java, an object is merely an instance of a Class having an identity, states, and behaviors.

  • Identity — The name by which an object is identified.
  • States — States are properties of an object. Example: A dog has states - name, color, weight.
  • Behaviors — Behaviors are methods (functions). Example: A dog has behaviors - barking, eating, running.

In the real-world example, everything around us - cars, animals, birds, humans are objects. All objects have identities, states and behaviors.

Similarly, Java objects have identities, states and behaviors. Identities are names given to objects, states are stored in the object's fields and behaviors are shown via methods.


How are objects created in Java?

In Java, objects are created using the new keyword.

Syntax for creating an object:

<ClassName> <objectName> = new <ClassConstructor()>


Let's create a class called "Dog" that has some characteristics, such as a name, color, and weight. We'll also add some actions that a dog can perform, such as barking, eating, and running.

public class Dog {

    /* These are states of the dog object */
    String name = "Tommy";
    String color = "brown";
    double weight = 20.5;

    /* These are behaviors of the dog object */
    
    void barking() {
        System.out.println(this.name + " is barking");
    }

    void eating(String food, double newWeight) {
        this.weight = this.weight + newWeight;
        System.out.println(this.name + " is eating " + food +
            ". His new weight is " + this.weight);
    }

    void running(int speed) {
        System.out.println(this.name + " is running at the speed of "
        + speed + " miles per hour");
    }

    /* Returning the object's state via a method */
    String getColor() {
        return color;
    }

}


Now, create another class called "Animal" and within that class, we will create an object of the Dog class.

public class Animal {

    public static void main(String[] args) {

        Dog dog = new Dog();

        String food = "biscuit";
        double newWeight = 1.2;
        int speed = 10;

        // invoking methods on dog object
        dog.eating(food, newWeight);
        dog.barking();
        dog.running(speed);

        String dogColor = dog.getColor();
        System.out.println(dogColor);
    }
}

The output of the above code is as follows:

Tommy is eating biscuit. His new weight is 21.7
Tommy is barking
Tommy is running at the speed of 10 miles per hour
brown


Creating of an object using the new keyword is also called instantiating of an object from a class.


Objects Naming Convention in Java

There are different naming convention in every programming languages. In Java, an object name must always be in the camelCase form.

Camel case is a naming convention in which the first letter of each word in a compound word is in uppercase except the letter of first word. Example: myObject, dateTime, createDate, totalAmount.