What is a class?
Class definition
A class is a set of parameters and methods that define the abstraction of an object. A class has the following elements:
- Fields: these are the parameters
- Constructor: method that creates a new class object. A constructor can accept input parameters to initialize
- Methods: functions that can use the fields values to compute required outputs or update its own fields
Difference between class and object
- An object is an instance of a class
- Each object is independent of any other object of the same class
Ways to create an object
There are several ways to create an object:
- Using the
new
operator: the most common way to create an object in Java. - Using the
clone()
method: if you want to create a copy of an existing object.- To use it, implement the
Cloneable
interface in your class and override theclone()
method
- To use it, implement the
- Using
factory
methods: it is astatic
method that returns an instance of a class- Factory methods are often used to create objects when you need more flexibility or control over the object creation process
- Using
reflection
: feature of the Java language that allows you to inspect and manipulate the structure of a class at runtime.- To use it, invoke the
newInstance()
method on the Constructor object for a particular class
- To use it, invoke the
- Using
deserialization
: create an object from its serialized form, which is a stream of bytes that represents the object’s state- This method allows to persist the state of the execution and retrieve it when requested
- To use it, the class must implement the
Serializable
interface and useObjectInputStream
andObjectOutputStream
classes to serialize and deserialize the object