Java Object Creation: Classes, Objects, Constructors, and Main Method

WHAT IS OBJECT CREATION? How is an Object Created in Java? A class provides the blueprint for objects. An object is a real-world instance created from that class. In Java, we use the "new" keyword to create objects. There are three important steps in object creation: 1. Declaration A reference variable is declared with the class type. Example: Car c1; 2. Instantiation The "new" keyword is used to allocate memory in RAM. Example: new Car(); 3. Initialization The constructor is called to initialize the object. Example: Car c1 = new Car(); General Syntax: class_name object_name = new class_name(); Example: Car c1 = new Car(); Here: Car → Class c1 → Reference variable new → Allocates memory Car() → Constructor Important Note: Even if a class contains multiple methods, they will not execute automatically. For execution to begin, the program must contain a main() method. The main() method gives Control Of Execution (COE). MAIN METHOD IN C LANGUAGE: #include <stdio.h> void main() { printf("HELLO WORLD"); } In C, execution begins from main(). MAIN METHOD IN JAVA: Basic Rule: Every method in Java must be inside a class. Correct Java main method structure: public static void main(String[] args) Let’s understand step by step why each keyword is required. Step 1 – public If main is not public, JVM cannot access it. So we attach PUBLIC to make it visible. Step 2 – static If main is not static, JVM cannot call it without creating an object. So we attach STATIC to make it accessible without object creation. Step 3 – void main does not return any value, so return type is void. Step 4 – String[] args JVM looks for this exact identifier. It represents command line arguments. It is an array of Strings used to collect input data. args is a dynamic array that stores values passed from command line. Initially, args is empty. Different Valid Main Method Signatures: public static void main(String[] args) static public void main(String[] args) public static void main(String args[]) public static void main(String... args) All are valid. Key Points to Remember • Save the file with the same name as the class containing main(). Example: Demo.java • Compile using: javac Demo.java This generates Demo.class (bytecode file). • Run using: java Demo JVM converts bytecode into machine-level code. • If main is not public → Error: main method not found. • If main is not static → Error: main method is not static. Quick Summary: Class → Blueprint Object → Instance of class new → Creates object Constructor → Initializes object main() → Entry point of program String[] args → Command line arguments javac → Compiles source code java → Executes bytecode #java #OOPS #Coding

  • diagram

To view or add a comment, sign in

Explore content categories