Object and Class in Java

Class in Java

A class is used to specify the properties and behavior of an object. Using variables, we can implement the properties of an object, and by using methods, we can implement the behavior of an object.

Note- A class is like a blueprint using which we can create objects.

Syntax of a class

class class_name
{
	attributes;
	methods;
}	

Important points you must remember

  • A class name starts with keyword class.
  • The keyword class is case sensitive. class isn't same as Class.
  • The file that contains your coding is called source file, and it must have .java extension.
  • A source file can have one or more classes or interfaces. Also, a source file cannot define more than one public class or interface.
  • If there is one public class or interface in the file, then the filename must match the name of this public class or interface.
  • When the source file is compiled , it generates one class file corresponding to each class in the source file. The name of the generated class file matches the name of the corresponding class in the source file.

Object in Java

The object is an instance of a class. An object is instantiated with the new operator. Whenever an instantiation is performed, a heap memory address value to that object is returned and assigned to the reference variable.

Using object reference variable, you can access object's attributes with the help of dot (.) operator.

Example

class Employee
{
	int id;
	String name;
	public void setId(int i)
	{
		id=i;
	}
	public int getId()
	{
		return id;
	}
	public void setName(String n)
	{
		name=n;
	}
	public int getName()
	{
		return name;
	}
	public static void main(String args[])
	{
		Employee e = new Employee();
		e.setId(1);
		e.setName("Keshav");
		System.out.println("Employee ID = "+e.getId());
		System.out.println("Employee Name = "+e.getName());
	}
}

Output

Employee Id = 1
Employee Name = Keshav