- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
5 different ways to create objects in Java
Consider a class Tester which has implemented Cloneable interface. Now you can initialize an object using following five ways:
1. Using new keyword.
Tester tester1 = new Tester();
2. Using Class.forName() method
Tester tester2 = (Tester)Class.forName("Tester").newInstance();
3. Using clone method.
Tester tester3 = tester1.clone();
4. Using Constructor.forName() method
Tester tester4 = Tester.class.getConstructor().newInstance();
5. Using Deserialization
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream ); Tester tester5 = (MyObject) objectInputStream.readObject();
Using new keyword is the most preferred one.
Advertisements
To Continue Learning Please Login
Login with Google