What is an object, an instance or a class in OOP?

In this tutorial we are going to define the concept of object, instance and class in the object oriented programming.

For this we are going to use an example where we are going to keep information about a dog. Using the information we have learned until now we are going to keep the information in local variables in our main method;

package com.edu4java.tutorial11;

public class Tutorial11 {
	public static void main(String[] args) {
		// local variables
		String name = "Coco";
		String colour = "brown";
		double weight = 1.5;
        
        	String name2 = "Rope";
		String colour2 = "green";
		double weight2 = 50;
	}
}

In this code we are keeping the information of two dogs easily, but imagine if we want to keep the information of 10 dogs...we would have 30 variables and the code would be a lot less legible.

To avoid this, in object oriented programming a new concept was created which associated data; the Class. A class is a mould from which we can create an object or an instance. In this case we would have the Class Dog, from which we would create an object which would have associated all the variables defined in the Class Dog.

package com.edu4java.tutorial11;


/**
 * @author Eli
 * A class is a mould from which we can create objects or instances
 * An object is an instance of a class
 */
public class Dog {
//object variables
	
	public String name;
	public double weight;
	public String colour;
	
	}
}

We now create a new object and we keep it in a Dog type variable. At this moment the variables associated to this object are created. In them we can keep the information of our dog; name, colour and weight.

package com.edu4java.tutorial11;

public class Tutorial11 {

	public static void main(String[] args) {

		Dog dog1 = new Dog();
		dog1.name = "Coco";
		dog1.colour = "brown";
		dog1.weight = 1.5;
		
		Dog dog2 = new Dog();
		dog2.name = "Rope";
		dog2.colour = "green";
		dog2.weight = 50;
		
        	printToConsole(dog1);
		printToConsole(dog2);

	}

	private static void printToConsole(Dog dog) {
		System.out.println();
		System.out.println("name: " + dog.name);
		System.out.println("colour: " + dog.colour);
		System.out.println("weight: " + dog.weight);

	}
	}

}

We now have two objects which belong to the same class Dog. Each of them is kept in a different variable; dog1 and dog2. To see how it works, I have created a method which prints them to the console; printToConsole(Dog dog).

<< Previous Next >>