Java – Classes and Objects

Objects and Classes in Java

We are going to cover classes and objects in Java. First, keep in mind that Java is an Object Oriented Programming(OOP) language.

Content


1. Objects in Java

Objects in Java are representations of real-world objects. Think of objects around you. Some are table, books, chair, computer, mouse, dog, phone and lots more. Since there are not data types for all of these, we can use objects to represent them in Java.

An object must therefore have two things:

  • attributes
  • behavior

For example a phone has a model and color(attribute). A phone can make calls (behavior). An animal has type(attribute), color (attribute). Also, an animal can make sound (behavior), can move(behavior).

Now, an object can be create in Java using Classes

2. Classes in Java

You can create objects in Java by defining a class. A class provides a definition for the attributes and behavior of objects. Attributes are represented as method. Similarly, behavior is represented as methods. Let’s take an example.

public class Animal {
	int numberOfLegs; //local variable 
	static int numberOfAnimals; //class variable
	String animalType;
	
	public void MakeSound() {
	}
	
	public void Move() {
		
	}

	public void Attack() {
		
	}
}

Listing 1.0: Animal class in Java

A class can have the following three elements.

Local Variables : These a variables defined inside a method. For instance, numberOfLegs in the animal class.

Instance Variables: These are variables defined outside a method. We use them with an instance or object of the class.

Class Variables: These variables belong to a class. Class variables are defined within a class. Therefore, you define them using static keyword. For example, numberOfAnimals.

3. Constructors in Java

All Java classes have a constructor. If however, you don’t provide a constructor, then a default constructor is available. A constructor is a special function defined in a class. We use a constructor to create new objects. Each time you create a new object, you invoke a constructor. Take for example the code in Listing 1.1.

public class Vehicle {
	public String make;
	public String model;
	
	public Vehicle(String make) { //a constructor
		this.make = make;
	}
}

Listing 1.1: Vehicle class with a constructor

Note the following about constructors:

  • the constructor has the same name with the class
  • you don’t specify any return value for constructors

Furthermore, you can have more than one constructor in a class. However, the difference would be in the number of parameters.

public class Vehicle {
	public String make;
	public String model;
	
	public Vehicle() {
		
	}
	
	public Vehicle(String make) { //constructor with one parameter
		this.make = make;
	}
}

Listing 1.2: Class with two constructors

You can play around with these codes. But we would take some examples later.

Finally we would see how to create new objects. This we would see in the next tutorial.