Object-Oriented Programming in Java

Java is a fully object-oriented language. Every program has at least one class. Classes are instantiated to create objects.

To provide a more tangible analogy, think of an automobile assembly line. Cars are created in factories. A group of engineers and others designed every detail of the car i.e. created a blueprint for the car. All cars are produced to the exact specifications with the possibility of customizations such as color, leather interior, sound system, sunroof, etc. The factory is the Java compiler. The blueprint is the class. Each individual car coming off the assembly line is an object. A class can be used to create infinite number of objects. Depending on the code of the class, objects can have different properties such as the color of the car. The act of creating an object is called instantiation.

A class is declared with the keyword class.

class MyClass {
    // some code
}

Objects are instantiated with the new keyword.

MyClass mc = new MyClass();

Time for an example. We will be creating a calculator:

public class Calc {
	int operand1;
	int operand2;
	int result;
	
	Calc() {
		this.operand1 = 1;
		this.operand2 = 2;
		this.result = 0;
	}
	
	void calculate() {
		this.result = this.operand1 + this.operand2;
	}
	
	int getResult() {
		return this.result;
	}
}

Save this as Calc.java. The name of the file must be the same as the name of the class.

public class testCalc {
	public static void main(String[] args) {
		Calc c = new Calc();
		c.calculate();
		System.out.println(c.getResult());
	}
}

Save this as testCalc.java. Compile and run both. The output should be the number 3.

In Calc.java, operand1, operand2, and result are are data members of the class. They are variables of type int.

Calc() is the constructor. It serves to initialize a class. Note that it does not have a return type i.e. no void, int, etc. in front of the method name. A constructor has the same name and the class. Note that the constructor is assigning default values to the data members.

calculate() sums operand1 and operand2 and stores the result in result. Note that they are accessed with "this" operator. "this" is a reference to the current object. Without, "this" Java will return an error since it won't be able to see outside the method and the variable is not declared in the method. "return" returns the value to the caller. In this code, the caller is a testCalc object.

The code begins at testCalc since it contains the "main" method. Line 3 instantiates the class Calc and creates the object c. During instantiation, the class is created and the constructor is called. The constructor sets the default values of the data members. Line 4 calls the calculate() method. calculate() sums the two numbers and saves the result with Calc object. Line 5 calls the getResult() method which prints the result to screen.