Objects and Classes are two core concepts of object oriented programming. In OOPs, We design a program using classes and objects. A programming language is said to be truly Object oriented programming language if everything is represented as Object. One of the fundamental concept of the object oriented programming approach is to break complex real world problems into smaller objects which represents real world entities.
In this tutorial, we will discuss about objects and classes in java programming language.
- A class is a template or blueprint which is used to create objects. It specifies the schema of an object by encapsulating the data and functions for manipulating this data in a single entity.
- Classes provides ability to define your own data types that better correspond to the problem being solved.
- Classes are extension of structures, like structure a class contains data members but can contains member functions also.
- A java class uses variables to define data fields(properties) and methods to define actions(behaviour).
- A java class can have fields, methods, static blocks, constructor methods and inner classes.
- We can think of a class as design document of a car, which contains details about the internal design and behaviour of a car like measurements of components, engine details etc. Using this design, anyone can manufacture a car. We can create any number of cars based on this design, each car will be identical. An car is an instance of design document.
Syntax of Declaring a Class
class class_name { // Class Body // Member Fields & Methods }
- Keyword "class" is used in declaration of a class.
- class_name is any valid java identifiers.
- Members fields are variables which defines the state of an object. These variables are also known as instance variables. Each object of a class will have it's own copy of instance variables.
- Member methods contains the logic of manipulating the state of the object. Public methods acts as an interface for external world to interact with object.
Here is an example of a "Box" class. It contains three fields(length, width and height) to represent the state of a real world Box. It contains a method calculateVolume(), it defines the interface for external world to get the volume of a box.
We can create many box objects(instances) using Box class as template.
public class Box { float length; float width; float height; float calculateVolume() { return length*width*height; } }
- Class name should be noun. The first letter of class name should be uppercase character. If class name have multiple words then each word will start with uppercase character.
For Example : Person, Chair, Computer etc. - The public class name should be same as the name of the source file which is appended by .java.
For Example: For a class SmartPhone, the source file name must be SmartPhone.java.
Objects in Java
An object is an programming representation of an real world entity like car, dog, fan etc. All these objects have some state and behavior.
Let's take an example of Car, it's state is color, weight, engine type, manufacturer name etc and it's behaviors are braking, turning, starting and stopping, running etc.
We can model any real world entity in terms of it's state and behaviors. As objects in OOPs represents real world entities, here state of is represented by member variables and behavior is implemented as member methods.
An object is an instance of a class. In other words an object is a variable of class data type. We can create as many objects of a class.
Class definition does not allocate any memory, when we create objects of a class then actually memory gets allocated.
Syntax of Declaring an Object
Keyword "new" is used to create an object of a class. Here is the syntax to create an object:
Class_Name objectReference = new Class_Name();
- Class_Name is the name of the class for which we are creating object.
- objectReference can be any valid java identifier.
- new keyword is used to create an object.
- new keyword is followed by a call to the constructor method of Class_Name. We can also call parametrized constructor of Class_Name to initialize object by passing some initial value.
Box b1 = new Box();
Access Members of an Object
We can use . operator to access the fields and methods of a object. Only public fields and methods of an object can be accessed using . operator. We will discuss about access modeifies(provate, public and protected access) in nect tutorial.
objectReference.fieldname objectReference.methodname
Java class and object example program
class Box { // Member fields long length; long width; long height; // Member method long getVolume() { return length*width*height; } } public class ClassAndObject { public static void main(String[] args) { // Create an Object of class Box Box boxObject1 = new Box(); Box boxObject2 = new Box(); // Initialize fields of boxObject1 object boxObject1.length = 5; boxObject1.width = 4; boxObject1.height = 6; // Initialize fields of boxObject2 object boxObject2.length = 2; boxObject2.width = 3; boxObject2.height = 4; //Call getVolume method of box object long volume1 = boxObject1.getVolume(); long volume2 = boxObject2.getVolume(); System.out.println("Volume of Box1= " + volume1); System.out.println("Volume of Box2= " + volume2); } }Output
Volume of Box1= 120 Volume of Box2= 24
In above program, we have created a class called "Box" which contains three fields(length, width and height) and one method getVolume.
Inside main method, we cretad two object of Box class boxObject1 and boxObject1 by calling default constructor of Box class. Each object of Box class will have its own copy of member fields. We then initialized the fields of box objects using the dot(.) operator. After initialization, we invoked the getVolume method of boxObject1 and boxObject2 to print the volume of box.
Best Practices for Using Class and Object in Java
- Encapsulate Data : Use encapsulation to protect the internal state of an object. Make attributes private and provide public methods to access and modify them.
- Use Constructors Effectively : Design constructors to initialize object states effectively. Consider using parameterized constructors for flexibility.
- Follow Naming Conventions : Follow Java naming conventions for classes, variables, and methods. Class names should start with an uppercase letter, and variable/method names should start with a lowercase letter.
- Favor Composition over Inheritance : Prefer composition when building class relationships to avoid potential issues associated with deep class hierarchies.
Conclusion
Understanding classes and objects is fundamental to Java programming and object-oriented design. Classes provide a blueprint for creating objects, and objects represent instances of those classes. By organizing code into classes and objects, developers can create modular, reusable, and maintainable software. As you continue your journey in Java development, practice creating classes, designing meaningful objects, and exploring the relationships between them to build robust and scalable applications.