Introduction
- In Java, we declare everything in terms of classes and objects.
- An object is an entity that possesses its own state and behavior.
- State represents characteristics of an object whereas, Behavior represents functionality of an object.
- In terms of java, object is a copy of non static members.
- Non-static data members represent state of an object whereas non-static function member represents behavior of an object.
- Class acts as a container for object state and behavior.
- We also refer to an object as an instance of the class. in java.
javapublic class TV { String company="SONY"; double price=35000.50; boolean isSmartTv=true; void displayPicture(){ System.out.println("Display Picture"); } } class MainApp{ public static void main(String[] args) { TV t1=new TV(); System.out.println("Company Name : "+t1.company); System.out.println("Price : "+t1.price); System.out.println("Is Smart Tv? : "+t1.isSmartTv); t1.displayPicture(); } }
Output:
Company Name : SONY
Price : 35000.5
Is Smart Tv? : true
Display Picture
Different ways to create objects in Java
You can declare objects in Java based on your code’s specific requirements using multiple ways. Here are some of the common ways to declare objects in Java:
Using new keyword:
- The most common and widely used way to create an object in Java is by using the new keyword. Consequently, creating an object with this method enables us to call the constructor of the specific class. Moreover, most of the time, objects in Java are created using this method.
- A reference variable stores the address of an object, and in this case, ‘obj’ serves as the reference variable storing the object’s address.
javaClassName obj=new ClassName();
What is the use of new keyword?
- We usually create object using new keyword.
- Moreover, the new keyword allocates memory for non-static members and loads non-static members into the memory.
- Additionally, it also calls the constructor of the class.
Anonymous Object:
- You declare and instantiate an anonymous object without assigning it to a variable.
javanew ClassName().methodName();
Using clone() method:
- If the class implements the Cloneable interface, you can create a new object that is a copy of an existing object using the
clone()
method.
- If the class implements the Cloneable interface, you can create a new object that is a copy of an existing object using the
javaClassName originalObj = new ClassName(); ClassName clonedObj = (ClassName) originalObj.clone();
-
Using newInstance() method:
- Creating an object using the newInstance() method is possible in Java. Additionally, this method is part of the Class class and is used to dynamically create an instance of a class.
javaClass myClass=Class.forName("MyClass"); MyClass obj=(MyClass) myClass.newInstance();