Java is an object oriented programming (OOP) language, and the OOP-paradigm utilizes classes as a template for programmer defined data types. Classes are often referred to as a blueprint and an instance of a class is called an object. When classes are setup they typically contain instance variables, and methods. The instance variables of a class are commonly called fields or attributes, while the methods of a class are referred to as functions or behaviors. Consider the following sample class called Car, it has two attribute 1. currentSpeed and 2. isRunning. Additionally, it has four behaviors 1. startCar() 2. shutOffCar() 3. speedIncrease() and 4. speedDecrease().
public class Car
{
private int currentSpeed; //attribute of an instance of Car is its current speed
private boolean isRunning; //attribute of an instance of Car is whether it is running
public void startCar() //behavior of an instance of Car is to start up
{
isRunning = true;
}
public void shutOffCar() //behavior of an instance of Car is to turn off
{
if(currentSpeed > 0)
{
System.out.println("The car is moving at " + currentSpeed + " mph!");
System.out.println("Bring the car to a stop before turning it off.");
}
else
isRunning = false;
}
public int accelerate(int speedIncrease) //behavior of an instance of Car is to go faster
{
if(!isRunning)
{
System.out.println("The car is not running");
return 0;
}
return currentSpeed += speedIncrease;
}
public int decelerate(int speedDecrease) //behavior of an instance of Car is to go slower
{
if(currentSpeed - speedDecrease < 0)
return currentSpeed = 0;
return currentSpeed -= speedDecrease;
}
}
Topics of Note
The instance variables in the above Car class have visibility modifiers set to private. Private restricts access to these variables so they can only be accessed by the Car class or by a public method of the Car class. This is an (OOP) concept known as encapsulation, or information hiding. We don't want outside classes to have direct access to the instance variables of the Car class, but we do want external classes to interact with our Car class.
Real World Example:
Can you read the time on a watch? Can you set the time on a watch? These are examples where you can interact with a watch but you do not have direct access to how the internal mechanisms of the watch works. We can represent this example by defining a class as: public class Watch which has attributes hour, minute, seconds and has behaviors getTime() and setTime().
How do you get time? You read the position of the hands on the face of a watch.
How do you set time? You rotate the crown to reposition the hands on the face of the watch.
All said and done, you still do not know the inner workings of a watch, and you don't need to, this is an example of how encapsulation works. You don't need to know the inner workings of the watch and the watch designer doesn't want you to because you would probably do harm to the system if you tinkered around with it.