In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class.
In this article, we will discuss Java objects and classes and how to implement them in our program.
A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class while a particular student named Ravi is an object.
If you’re looking to gain a deeper understanding of Java and its object-oriented principles, exploring a comprehensive Java Programming Online course can be a valuable step. It will help you master the core concepts of classes and objects, and how to effectively use them in building robust Java applications.
also instance variable) also instance variable) Example 2
Example 3
0 null
Output 1
0
null
Output 2
GeeksForGeeks
Output 3
GeeksForGeeks
In general, class declarations can include these components, in order:
Constructors are used for initializing new objects. Fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real-time applications such as nested classes , anonymous classes , and lambda expressions .
An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities. Objects are the instances of a class that are created to use the attributes and methods of a class. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of :
Example of an object: dog
Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, and “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”.
Note: When we create an object which is a non primitive data type, it’s always allocated on the heap memory.
When an object of a class is created, the class is said to be instantiated . All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.
Example:
Java Object Declaration
As we declare variables like (type name;). This notifies the compiler that we will use the name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variables , the type must be strictly a concrete class name. In general, we can’t create objects of an abstract class or an interface.
Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object.
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.
Example:
Hi my name is tuffy. My breed,age and color are papillon,5,white
Initialize by using method/function:
Software name is: Visual studio Software price is: 0.0
This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the class and it has no return type. The Java compiler differentiates the constructors based on the number and the type of the arguments. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”, “papillon”,5, and “white” as values for those arguments:
Dog tuffy = new Dog("tuffy","papillon",5, "white");
The result of executing this statement can be illustrated as :
Memory Allocation of Java Objects
Note: All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent’s no-argument constructor (as it contains only one statement i.e super();), or the Object class constructor if the class has no other parent (as the Object class is the parent of all classes either directly or indirectly).
There are four ways to create objects in Java. Strictly speaking, there is only one way(by using a new keyword), and the rest internally use a new keyword.
It is the most common and general way to create an object in Java.
Example:
// creating object of class Test
Test t = new Test();
There is a pre-defined class in java.lang package with name Class. The forName(String className) method returns the Class object associated with the class with the given string name. We have to give a fully qualified name for a class. On calling the new Instance() method on this Class object returns a new instance of the class with the given string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
clone() method is present in the Object class. It creates and returns a copy of the object.
// creating object of class Test
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();
De-serialization is a technique of reading an object from the saved state in a file. Refer to Serialization/De-Serialization in Java
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();
In real-time, we need different objects of a class in different methods. Creating a number of references for storing them is not a good practice and therefore we declare a static reference variable and use it whenever required. In this case, the wastage of memory is less. The objects that are not referenced anymore will be destroyed by the Garbage Collector of Java.
Test test = new Test();
test = new Test();
In the inheritance system, we use a parent class reference variable to store a sub-class object. In this case, we can switch into different subclass objects using the same referenced variable.
Example:
class Animal <>
class Dog extends Animal <>
class Cat extends Animal <>
public class Test
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
>
Anonymous objects are objects that are instantiated but are not stored in a reference variable.
btn.setOnAction(new EventHandler()
public void handle(ActionEvent event)
System.out.println("Hello World!");
>
>);
The differences between class and object in Java are as follows:
Mastering the concepts of classes and objects is essential for any Java programmer. These foundational elements of Java allow for the creation of robust and scalable software designs. Understanding how to effectively use classes and objects can help you write more organized and modular code, which is easier to manage and extend.