
Java OOPs Basics: Understanding Classes, Objects, and Methods By SUDBTECH
Java Classes and Objects
In Java, classes and objects are the foundation of Object-Oriented Programming (OOP). They help us represent real-world things in a structured way.
Java Classes
A class in Java is a blueprint that defines the properties and behaviors of a group of similar objects. It acts as a template, but it does not store actual data. Instead, objects are created from this class.
For example, Cricketer is a class because all cricketers share common characteristics like name, team, and runs scored. However, a specific cricketer like Virat Kohli is an object of this class.
Properties of Java Classes
- A class is not a real-world entity; it is just a model.
- It does not occupy memory until an object is created.
- A class consists of variables (data members) and methods (functions) that define behaviors.
- A class in Java can contain:
- Data members (variables like name, runs, team)
- Methods (functions like batting() or bowling())
- Constructors (special methods to initialize objects)
- Nested classes (a class inside another class)
- Interfaces (used for abstraction and multiple inheritance)
Java Objects
An object is a real-world example of a class. It is an instance of a class that holds actual values for the defined properties.
For example, if Cricketer is a class, then:
- Object 1: name = "Virat Kohli", team = "India", runs = 14000
- Object 2: name = "Rohit Sharma", team = "India", runs = 10000
Each object has its own unique data but follows the same structure defined by the class.
Difference Between Class and Object
A class is a blueprint for creating objects. An object is a real-world instance of a class.
It does not store actual data. It holds real values for its properties.
Memory is not allocated when a class is created. Memory is allocated when an object is created.
Class Defines what properties and behaviors an object should have. Whereas Object Performs actual actions using the defined behaviors.
Example: class Cricketer { String name; int runs; } , Example of object: Cricketer Virat Kohli = new Cricketer();
Components of a Java Class (Explained Simply)
A Java class is made up of different parts. Each part has a specific role in defining how the class works. Let's break them down in an easy way.
1. Modifiers
- These define the access level of the class.
- A class can be:
- public → Accessible from anywhere.
- Default (no modifier) → Accessible only within the same package.
Example:
public class Cricketer { // 'public' means this class can be accessed from anywhere }
2. class Keyword
- The class keyword is used to declare a class in Java.
Example
class Car { // 'Car' is a class }
3. Class Name
- The name of the class should start with a capital letter (by convention).
- It should be meaningful and follow Java naming rules.
Example:
class Student { // 'Student' is the class name }
4. Superclass (Parent Class) (Optional)
- If a class extends another class, it means it inherits properties and methods from that class.
- The parent class is mentioned using extends.
- Java only allows one superclass (single inheritance).
Example:
class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } // 'Dog' class extends 'Animal' class (inherits its behavior) class Dog extends Animal { }
5. Interfaces (Optional)
- A class can also implement multiple interfaces using implements.
- Interfaces define behaviors that a class must follow.
Example:
interface Player { void play(); // Method without body (to be implemented by class) } // 'Cricketer' class implements 'Player' interface class Cricketer implements Player { public void play() { System.out.println("Playing cricket"); } }
6. Class Body { }
- The main code of the class goes inside curly braces { }.
- It contains variables, methods, constructors, etc.
Example:
class Car { int speed; // Variable (field) void run() { // Method System.out.println("Car is running"); } }
7. Fields (Variables)
- These store data about the object.
- Each object of the class has its own values for these fields.
Example:
class Cricketer { String name; // Field (variable) int runs; }
8. Methods (Functions)
- Methods define the behaviors of the class.
- They allow the object to perform actions.
Example:
class Cricketer { void bat() { System.out.println("Cricketer is batting"); } }
9. Constructors
- A constructor is a special method used to initialize an object.
- It runs automatically when an object is created.
Example:
class Cricketer { String name; // Constructor Cricketer(String playerName) { name = playerName; } }
Example Code for Class and Object in Java
// Defining a class class Cricketer { String name; String team; int runs; // Method to display player details void showDetails() { System.out.println("Name: " + name); System.out.println("Team: " + team); System.out.println("Runs: " + runs); System.out.println("----------------------"); } } // Main class to create objects public class Main { public static void main(String[] args) { // Creating first object - Virat Kohli Cricketer player1 = new Cricketer(); player1.name = "Virat Kohli"; player1.team = "India"; player1.runs = 12000; // Creating second object - Rohit Sharma Cricketer player2 = new Cricketer(); player2.name = "Rohit Sharma"; player2.team = "India"; player2.runs = 10000; // Displaying details of both players player1.showDetails(); player2.showDetails(); } }
Expected Output:
Name: Virat Kohli Team: India Runs: 12000 ---------------------- Name: Rohit Sharma Team: India Runs: 10000 ----------------------
- Explanation
- Class Cricketer is created
- It defines common properties like name, team, and runs.
- It also has a showDetails() method to print details.
- Objects player1 and player2 are created
- player1 represents Virat Kohli with actual values.
- player2 represents Rohit Sharma with actual values.
- Method showDetails() is used to display details
- When we call player1.showDetails(), it prints Virat Kohli’s details.
- When we call player2.showDetails(), it prints Rohit Sharma’s details.
- Class Cricketer is created
Java Class Methods
So, in Java, methods are basically blocks of code that do something when you call them. You put them inside a class, and they help you avoid repeating the same code again and again.
Example: Creating a Method
Let’s say we have a method called myMethod() inside a class called Main:
public class Main { static void myMethod() { System.out.println("Hello World!"); } }
This method just prints "Hello World!" when you call it. To call it, you just use its name followed by () like this:
Calling the Method in main()
public class Main { static void myMethod() { System.out.println("Hello World!"); } public static void main(String[] args) { myMethod(); // Calling the method } }
Output:
Hello World!
Static vs. Public Methods
You'll see static and public methods in Java.
- Static methods → Can be used without creating an object of the class.
- Public methods → Need an object to be called.
Example: Static vs. Public
public class Main { // Static method static void myStaticMethod() { System.out.println("Static methods can be called without creating objects"); } // Public method public void myPublicMethod() { System.out.println("Public methods must be called by creating objects"); } public static void main(String[] args) { myStaticMethod(); // Works fine! // myPublicMethod(); ❌ This would cause an error Main myObj = new Main(); // Create an object myObj.myPublicMethod(); // Now it works! } }
Output:
Static methods can be called without creating objects Public methods must be called by creating objects
Accessing Methods with an Object
Let’s take an example with a laptop .
Create a Main class public class Main { // Method to power on the laptop public void powerOn() { System.out.println("The laptop is turning on..."); } // Method to display battery percentage public void batteryStatus(int battery) { System.out.println("Battery percentage: " + battery + "%"); } public static void main(String[] args) { Main myLaptop = new Main(); // Create an object of Main myLaptop.powerOn(); // Call the powerOn method myLaptop.batteryStatus(85); // Call batteryStatus with a value } }
Output:
The laptop is turning on... Battery percentage: 85%
Understanding the Code :
1️⃣ Class Definition
- public → This means the class can be accessed from anywhere in the program.
- class Main → We are creating a class named Main (Java programs always need at least one class).
2️⃣ Creating a Method (powerOn)
- public → This means this method can be used by objects of this class.
- void → This means it does not return any value, it just performs an action.
- powerOn() → The name of the method (method names should make sense).
- The method prints "The laptop is turning on..." when called.
3️⃣ Creating Another Method (batteryStatus)
- public void batteryStatus(int battery) → This method accepts an input (battery percentage).
- int battery → This means the method requires a number (integer) as input.
- The method prints the battery percentage that is passed to it.
4️⃣ The main() Method (Where Java Starts Execution)
- This is the starting point of every Java program.
- Java looks for this method first and runs the code inside it.
5️⃣ Creating an Object (Important Step)
- Main → The class name (because we are using methods inside this class).
- myLaptop → A name for the object (can be any name).
- new Main(); → This creates a new object of class Main.
- Objects allow us to use public methods inside the class.
6️⃣ Calling Methods Using the Object
- myLaptop.powerOn(); → Calls the powerOn() method and executes it.
- myLaptop.batteryStatus(85); → Calls batteryStatus(85) and prints the battery percentage (85%).
Key Takeaways
- Methods are reusable code blocks inside a class.
- Static methods don’t need objects, but public methods do.
- Methods can take parameters to work with different values.
- Calling a method executes the code inside it.
Final Conclusion: Java Classes and Objects
Understanding classes and objects is absolutely essential when learning Java and mastering Object-Oriented Programming (OOP). They form the core foundation that helps us model real-world systems using code in a structured, logical, and reusable way.
💡 What We've Learned
🔹 Java Classes
A class is like a blueprint or template. It defines:
- What properties (variables) an object will have
- What behaviors (methods) it can perform
Think of a class as a design – for example, a "Cricketer" class outlines what all cricketers should have (like name, team, and runs) and what they can do (like bat()).
Key concepts:
- Classes don’t occupy memory until objects are created.
- They can have variables, methods, constructors, and even implement interfaces.
- Classes can also inherit from other classes using the extends keyword (single inheritance).
🔹 Java Objects
An object is a real instance of a class. It holds actual data and uses the functionality defined by the class.
For example:
Cricketer player1 = new Cricketer(); player1.name = "Virat Kohli";
Here, player1 is an object of the Cricketer class and contains real values for its properties.
Each object is independent and has its own copy of instance variables.
🔹 Difference Between Class and Object
🔸 Class
- Blueprint / Template
- No memory allocated
- Defines structure & behavior
- Example: Cricketer
🔹 Object
- Real-world Instance
- Memory allocated
- Holds data & performs actions
- Example: Virat Kohli
⚙️ Key Components of a Java Class
- Modifiers (e.g., public)
- class keyword
- Class name (e.g., Car, Student)
- Superclass (optional): for inheritance
- Interfaces (optional): for abstract behaviors
- Body {}: where everything lives
- Fields: variables to store data
- Methods: define behavior
- Constructors: initialize objects
🔁 Java Methods Recap
- Methods allow code to be reused easily.
- Can be static (no object needed) or public (needs object).
- Can take parameters and return results.
- Called using object reference or directly (for static).
Example:
public void display() { System.out.println("Showing info..."); } Main obj = new Main(); obj.display(); // Calls the method
🧠 Why It Matters
Using classes and objects helps you:
- Build modular, clean, and reusable code
- Represent real-world scenarios easily
- Collaborate on large-scale software development
- Apply OOP principles: Encapsulation, Inheritance, Abstraction, and Polymorphism
📌 In Summary:
- Class = Plan, Object = Product
- You define a class once, but you can create many objects from it.
- Objects bring your programs to life by holding data and performing actions.
- Java encourages you to model your code after real-world things using classes and objects.
- Mastering this concept is the first big step toward becoming a proficient Java developer.
Thank You.
0 Comments