Object and Classes in Java with example

Java is a object oriented programming language, that means it solves problems by mapping them to real world objects.

An object-based Java application is a Java application whose design is based on declaring classes, creating objects from them, and designing interactions between these objects.

What is a class ?

In Java, a class is a template or blueprint that defines states(variables) and behavior(methods) of an object.
public class Dog {
	// State of an object
	String color;
	// Behaviour of an object
	public void bark(){
As shown in the example above, Dog is a class that defines state of a Dog i.e. color and behaviour of a Dog i.e. bark().

How to define a class ?

In java a class is defined using "class" keyword followed by its name and {}, the name should not be any reserved keyword.

In convention name of the class should start with a capital letter, if a name consists of multiple words, the first letter of each word is uppercased (such as EmployeeCategories). This naming convention is called camelcasing. i.e. Dog, Student, Employee, MyClass etc.
class ClassName
   // class body
Variables and Methods of the class goes inside opening '{' and closing '}' parenthesis.
public class ClassName {
	// variable
	String color;
	// Method
	public void bark(){

Rules for Java Class declaration.

A class can have only public or no access specifier. It can be either abstract, final or concrete (normal class). It may optionally extend one parent class. By default, each class extends java.lang.Object.

It may optionally implement any number of comma-separated interfaces. Each .java source file may contain only one public class. A source file may contain any number of default visible classes. The source file name must match the public class name.

What is an Object ?

An Object is an instance of a class that has its own states and behaviour, different objects of a Dog class can be "germanShepherd", "bullDog". In Java object or instance of a class can be created using 'new' keyword.
Dog bullDog = new Dog();
The object bullDog will have physical existence and get memory in heap area. The new operator dynamically allocates memory for an object.

Is Java a pure object oriented language ?

There are lot of arguments around whether Java is purely object oriented or not. Java is now a purely object oriented language as it has wrapper classes. So one can use Integer, Float etc. instead of int, float etc. (there are a total of eight primitive types). But since Java has those eight primitive types, few critics says Java is not purely object-oriented.

About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.