Classes and Objects
Java Programs are all about Classes and Objects. Not only in Java but in any object oriented language Classes and Objects forms the basis of the language.
What is a Class?
A Class is a blueprint or a template for an object. A class has only two things – a state (instance variables) and behavior (methods).
State (Instance Variable) – Every Object (an instance of a class) will have its unique sets of instance variables as defined in the class.
Behaviour (Methods) – Methods are where programmers write logic. Methods are where actions are taken, and data gets modified.
Let us consider an example: Car is an example of a class. Every class has a state or properties – Every car will have a steering wheel, it will have four wheels and seats.
Now let’s consider another example to explain Classes and objects with Java. Let us create a class with name Employee, which has two instance variable: salary and bonus and a method to calculate total salary.
public class Employee { //Defining instance variable int salary; int bonus; //Creating a method to calculate salary void calculateSalary(){ int totalSalary; totalSalary = salary + bonus; System.out.println("Total Salary : "+ totalSalary); } }
In the above code, Employee is a class which tells how an object will look like, salary and bonus are two variables created in this class and calculateSalary() is the method created which has the logic to calculate total salary.
What is an Object?
An Object is an instance of a class. Every object will have a state as defined in a class and it will perform certain actions defined in a method.
Now consider an example of the Car says, FortFigo. It will be an object which will have a steering wheel and a seat and all other properties of a car.
Let us consider another example to explain objects with Java, below we created a class with the main method where we will be using the Employee class created above. Here, first create an instance of the Employee class and then will access the variables and methods.
package day3; public class DemoEmployee { public static void main(String[] args) { Employee saurabh; //new keyword is to instantiate (allocating memory to the variable) //Employee() - method (constructor) - Initializing default values. saurabh = new Employee(); saurabh.salary = 909090; saurabh.bonus = 8989; saurabh.calculateSalary(); //------------------------------------------------------ } }
In above code, saurabh is an object of class Employee.
saurabh.salary and saurabh.bonus are the variables to access salary and bonus variables of class “Employee” for saurabh object.
saurabh.calculateSalary() – is the method called to calculate salary for saurabh object.
PS: For any questions, queries or comments feel free to write us at support@qatechub.com or saurabh@qatechhub.com