Object and Classes

Object: As explained earlier in the post OOPs concept, Object can be defined as what we see around us in real world like car, pen, TV etc. It can be a physical and logical entity. Every object has a state and behavior.

Take an example of Car: A car has a state (color, model, name etc.) and behavior( driving, applying break etc.). Likewise, in programming language also we create the objects which meets the requirement of business and helps in re-usability, maintainability and robustness etc.

Class: It is a blueprint, from which an object can be created. A class is a group of objects.

Along with that a class can have the following:

  • Data members
  • Another class
  • Method
  • Constructor
  • block

Example of an object and class:

public class Employee {	
	String name; //Data member
	int age;   //Data member
	
	public static void main(String[] args) {
		Employee emp = new Employee();  // creating the object of Employee
		System.out.println(emp.name);   //print name 
		System.out.println(emp.age);    //print age
	}	
}
Output : null 0

Let’s take one more example , where we are creating the methods and calling that method by using 2 created objects emp1, emp2.

New keyword is used to create the object which assigns memory to it at run time.

public class Employee {	
	String name; //Data member
	int age;   //Data member
	
	public void displayRecord(String empName,int empAge){   // method
		name =empName;
		age =empAge;
		
		System.out.println(name +"---" + age);
	}
	
	public static void main(String[] args) {
		Employee emp1 = new Employee();  // creating the object of Employee
		Employee emp2 = new Employee();  // creating another object of Employee
		
		emp1.displayRecord("Employee 1", 25);
		emp1.displayRecord("Employee 2", 30);

	}	
}
Output : Employee 1—25
Employee 2—30
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...