Declaring and Instantiating Java Objects
In Java, an object is an instance of a class. To create an object, you need to:
- Declare a variable: This variable will hold the reference to the object.
- Instantiate the object: This is done using the
newkeyword followed by the class constructor.
// Declare a variable of type MyClass
MyClass myObject;
// Instantiate the object using the new keyword and the MyClass constructor
myObject = new MyClass();
Nested Classes
Java allows you to define classes within other classes. These are called nested classes. There are two types:
- Static nested classes: These behave like regular top-level classes.
- Inner classes: These have access to the members of the enclosing class.
class OuterClass {
// ...
class InnerClass {
// ...
}
}
// Instantiating an inner class object
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();


