Java language revolves around the Object Oriented Programming (OOP), the base of OOP is Classes and Objects. This post is dedicated to Understanding the need for OOP and about Classes and how that works.
As the programming languages made progress there was a need to making it more connected to real world and that is how Classes came into picture. A Class
is used to represent real world objects into programming languages. If you consider any real world object it can be described with two things State
and Behaviour
.
Let’s consider a Car object, the state of this Car can be described using multiple parameters. 4 wheels, parked car, car model, year made etc. These state of any object can be described in Class with the use of variables
and the behaviour of car that can be change gear, change speed, apply brake etc. can be described with the use of methods
Thus Class in Java comprises of member variables and methods. Lets see an example of Class to gain a better understanding.
public class Car { private String carModel; private String yearMade; private int speed; public void changeSpeed(int newSpeed){ this.speed = newSpeed; } public void applyBrake(){ System.out.println("Brakes Applied"); } }
If you consider the above Class example. carModel
, yearMade
and speed
these are called member variables and are used to define the state of the Car object. We have created two methods changeSpeed(int newSpeed)
and applyBrake()
by which we can alter the behaviour of the car object.
Creating and Using Objects
By creating a Class we have the prototype or blueprint of our object ready. We can use this Class to create one or many objects from it. Please see the following code to see how we can create objects.
public class Car { private String carModel = "Mitsibushi"; private String yearMade = "2012"; private int speed; public void changeSpeed(int newSpeed){ this.speed = newSpeed; System.out.println("New Speed of Car is "+newSpeed); } public void applyBrake(){ System.out.println("Brakes Applied"); } public static void main(String args[]){ Car car1 = new Car(); System.out.println("Car Model is "+car1.carModel); System.out.println("Year Made is "+car1.yearMade); car1.changeSpeed(60); car1.applyBrake(); } }
Please notice the changes made in this code from the previous code. If you consider the main method you can see how we create a new object from Class by using new
keyword. Car car1 = new Car();
, this statements means that we are creating a new object of type Car and the object will be stored in variable car1
Further you can see that the member variables and method of a Class can be accessed from our newly created object by dot(.)
operator.