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 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 to store different types of dogs in a pet store’s database, we would need to create different objects.
The following code creates different Dog
objects and stores them:
public class Dog {};
Dog GermanShephered = new Dog();
Dog Bulldog = new Dog();
Dog Labrador = new Dog();
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.
The following code initializes the Dog
objects and uses a few methods:
class Dog {// data members or stateString breed;int age;String size;String color;// methods or behaviorpublic 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 stateGermanShephered.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());}}
Free Resources