What is an object in Java?

An object is an entity that has a state, specific behavior, and has been created for a specific purpose. In the real world, an object can be imagined exactly as it is (e.g., chair, bike, table, and car).

An object’s relation with a class

An object is always a product of a class. The state of an object can be represented by data members, while the behavior can be represented by methods. Suppose there is a class named Dog that has several data members and methods. In order t​o store different types of dogs in a pet store’s database, we would need to create different objects.

The f​ollowing code creates different Dog objects and stores them:

public class Dog {};
Dog GermanShephered = new Dog();
Dog Bulldog = new Dog();
Dog Labrador = new Dog();

State and behavior

An object is not just a product of a class as it also contains​ the data members and methods of that class. The following illustration shows an example of what the data members and methods of the class Dog could be.

svg viewer

Code

The following code initializes the Dog objects and uses a few methods:

class Dog {
// data members or state
String breed;
int age;
String size;
String color;
// methods or behavior
public String getInfo() {
return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color);
}
void eat(){};
void sleep(){};
void sit(){};
void run(){};
public static void main(String[] args) {
Dog GermanShephered = new Dog();
GermanShephered.breed="German Shephered"; //Initializing and setting the state
GermanShephered.size="Small";
GermanShephered.age=2;
GermanShephered.color="Brown";
System.out.println(GermanShephered.getInfo());
Dog BullDog = new Dog();
BullDog.breed="Bull dog";
BullDog.size="Big";
BullDog.age=4;
BullDog.color="White";
System.out.println(BullDog.getInfo());
}
}
Copyright ©2024 Educative, Inc. All rights reserved