Java Part 8: Object-Oriented Programming In Java (Classes and Objects)

Java Part 8: Object-Oriented Programming In Java (Classes and Objects)


Please Subscribe Youtube| Like Facebook | Follow Twitter

Object-Oriented Programming In Java

In this article, we will provide a detailed overview of Object-Oriented Programming In Java (Classes and Objects) and provide examples of how they are used in Java programming.

Object-Oriented Programming (OOP) is a fundamental paradigm in software development, allowing developers to create modular, reusable, and efficient code. Java, being one of the most popular programming languages, fully supports OOP principles. In this article, we will explore the key concepts of object-oriented programming in Java, providing detailed explanations and real-world examples to help you grasp the concepts more effectively.

OOP is a programming paradigm that organizes code into objects, which are instances of classes. It emphasizes the concept of objects and their interactions to solve complex problems. OOP provides a modular and flexible approach to software development, enhancing code reuse and maintainability.

The Pillars of Object-Oriented Programming

OOP is built upon four key pillars: encapsulation, inheritance, polymorphism, and abstraction.

Encapsulation

Encapsulation is the process of bundling data and methods together within a class, hiding internal details and providing controlled access to the object’s state. It promotes data integrity and prevents direct manipulation of internal variables. In Java, you can achieve encapsulation using access modifiers like private, public, and protected.

Inheritance

Inheritance allows the creation of new classes (derived classes) based on existing classes (base classes). The derived classes inherit the properties and behaviors of the base class, promoting code reuse and creating an “is-a” relationship between classes. Java supports single inheritance, meaning a class can inherit from only one superclass.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables code to be written that can work with objects of multiple types, providing flexibility and extensibility. Polymorphism is achieved through method overriding and method overloading.

Abstraction

Abstraction is the fourth pillar of OOP and involves simplifying complex systems by focusing on essential features and hiding unnecessary details. It allows programmers to create abstract representations of real-world entities or concepts in the form of classes and interfaces. Abstraction provides a high-level view of an object’s behavior and characteristics, without specifying the implementation details. By abstracting away specific implementation details, abstraction promotes modularity, code reusability, and code organization.

We will explain them further in detail in next article. In this article we will explain Classes and Objects

Classes and Objects

In Java, classes are blueprints or templates that define the structure and behavior of objects. An object is an instance of a class, representing a real-world entity. Let’s explore how to define a class and create objects.

Defining a Class

A class declaration in Java consists of a class keyword, followed by the class name and a pair of curly braces. It can include fields (variables) and methods (functions) that define the object’s behavior.

Example

public class Car {
    // Constructors, methods, and fields can be defined here
}

Creating Objects

To create objects in Java, you need to use the new keyword followed by a call to the class constructor. The constructor initializes the object and sets its initial state. Here’s an example of creating objects of the Car class:

Car myCar = new Car();
Car friendCar = new Car();

In the above code, we created two Car objects named myCar and friendCar using the new keyword. Each object will have its own set of instance variables and methods.

Methods, Fields and Constructors

Methods are functions defined within a class that perform specific tasks or actions. Fields, also known as instance variables, hold the state or data associated with objects.

You can access methods and fields using the dot notation. The dot notation allows you to access members (methods and fields) of a class or object.

To access a method, you use the following syntax:

objectName.MethodName(arguments);

To access a field, you use the following syntax:

objectName.FieldName;

Constructors are special methods used to initialize objects. They have the same name as the class and do not have a return type. Constructors can take parameters to set initial values for the object’s fields. Constructors can be categorized into two main types: no-argument constructors, parameterized constructors.

No-Argument/Non-Parameterized Constructors

A no-argument constructor, also known as a default constructor, does not take any parameters. It initializes the object with default values or performs basic initialization tasks. If no constructor is explicitly defined in a class, Java automatically provides a default no-argument constructor. However, once you define a constructor with parameters, the default constructor is no longer generated automatically.

public class Car{
    public Car() {
        // Initialization code or default values
    }
}

Parameterized Constructors

Parameterized constructors are constructors that accept one or more parameters. They allow you to initialize the object with specific values provided during object creation. These values are passed as arguments to the constructor and used to set the initial state of the object.

public class Main {
    public static void main(String[] args) {
        //creating object with non argument constructor
        Car myCar = new Car("Toyota", "Camry", 2022);
        //creating object with one arguments constructor
        Car myCar2 = new Car("Toyota");
        //creating object with three arguments constructor
        Car myCar3 = new Car("Toyota", "Camry", 2022);
    }
}

class Car {
    private String make;
    private String model;
    private int year;

    //No-Argument or Non Parameterized constructor
    public Car() {
    }
    
    //Parameterized constructor with one parameters
    public Car(String make) {
        this.make = make;
    }

    //Parameterized constructor with three parameters
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
}

Let’s add some methods, fields and constructor to the Car class

Example

public class Car {

    // Fields
    private String make;
    private String model;
    private int year;
    
    // Constructor
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
    
    // Getter methods
    public String getMake() {
        return make;
    }
    
    public String getModel() {
        return model;
    }
    
    public int getYear() {
        return year;
    }
    
    // Setter methods
    public void setMake(String make) {
        this.make = make;
    }
    
    public void setModel(String model) {
        this.model = model;
    }
    
    public void setYear(int year) {
        this.year = year;
    }
    
    // Other methods
    public void startEngine() {
        System.out.println("Engine started!");
    }
    
    public void stopEngine() {
        System.out.println("Engine stopped!");
    }

    public void carDetails() {
        System.out.println("make:"+make+" model:"+model+" year:"+year);
    }
}

In the above code, we added getter and setter methods to access and modify the private fields (make, model, year). We also included additional methods like carDetails(), startEngine() and stopEngine() to perform specific actions. In our example, we added a constructor that takes make, model, and year as parameters.

this keyword

this keyword is a reference to the current object within a class. It is primarily used to differentiate between instance variables and parameters or local variables that have the same name.

i.e

this.make = make; 

This line assigns the value of the make parameter to the make attribute of the current object. The use of this is necessary when there is a naming conflict between the parameter and the attribute. It explicitly refers to the instance variable make of the current object, distinguishing it from the method parameter.

Now, we can create an instance of the Car class and call its methods. Here’s an example:

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", "Camry", 2022);

        myCar.startEngine();
        myCar.carDetails();
        myCar.stopEngine();
    }
}

To run Code

Step 1: Create a new file named Car.java and open it in a text editor or an integrated development environment (IDE).

Step 2: Copy and paste the Car class code into the Car.java file:

public class Car {
    // Fields
    private String make;
    private String model;
    private int year;
    // Constructor
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
    // Getter methods
    public String getMake() {
        return make;
    }
    public String getModel() {
        return model;
    }
    public int getYear() {
        return year;
    }
    // Setter methods
    public void setMake(String make) {
        this.make = make;
    }
    public void setModel(String model) {
        this.model = model;
    }
    public void setYear(int year) {
        this.year = year;
    }
    // Other methods
    public void startEngine() {
        System.out.println("Engine started!");
    }
    public void stopEngine() {
        System.out.println("Engine stopped!");
    }
    public void carDetails() {
        System.out.println("make:"+make+" model:"+model+" year:"+year);
    }
}

Step 3: Save the Car.java file.

Step 4: Create a new file named Main.java and open it in a text editor or IDE.

Step 5: Copy and paste the Main class code into the Main.java file:

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", "Camry", 2022);

        myCar.startEngine();
        myCar.carDetails();
        myCar.stopEngine();
    }
}

Step 6: Save the Main.java file.

Step 7: Compile the Car.java and Main.java files. In a command-line interface, navigate to the directory where the files are saved and run the following commands:

javac Car.java
javac Main.java

Step 8: Run the Main class. Execute the following command:

java Main

You should see the following output

Output

Engine started!
Make: Toyota | Model: Camry | Year: 2022
Engine stopped!

In the Main class, we create an instance of the Car class named myCar with the make “Toyota”, model “Camry”, and year 2022. The constructor initializes the object with the provided values. We then call the startEngine() method to start the car’s engine, followed by the carDetails() method to display the car’s details. Finally, we call the stopEngine() method to stop the car’s engine.

Static Method And Non-Static Method In Java

Static Method

A static method is a method that belongs to a class rather than an instance of the class. It can be accessed directly from the class itself without creating an instance. It does not have access to instance-specific data

Example Code:

public class Main {
    public static void main(String[] args) {
        int result = MathUtils.sum(3, 5);
        System.out.println(result); // Output: 8
    }
}

class MathUtils {
    public static int sum(int a, int b) {
        return a + b;
    }
}

Output

8

Non-Static Method

A non-static method is a method that belongs to an instance of a class. It can access instance variables and other non-static methods. Therefore It has access to instance-specific data

Example Code:

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);
        double area = circle.calculateArea();
        System.out.println(area); // Output: 78.53981633974483
    }
}

class Circle {
    private double radius;
    public Circle(double radius) {
        this.radius = radius;
    }
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

Output

78.53981633974483

Differences between static and non-static methods in Java.

TermStatic MethodNon-Static Method
InvocationInvoked using class nameInvoked using an instance of the class
AccessibilityAccessible from class directlyAccessed through an instance of the class
Instance DependencyDoes not have access to instance-specific dataCan access instance variables and methods
Memory AllocationStored in a separate memory area (method area)Each instance has its own copy (heap memory)
Object InteractionNo interaction with instance-specific dataCan interact with instance-specific data
Method OverridingCannot be overridden in a subclassCan be overridden in a subclass

Conclusion

In conclusion, classes and objects are the fundamental building blocks of object-oriented programming (OOP). They enable us to organize and structure our code in a way that closely mirrors real-world entities and their interactions. By encapsulating data and behavior within classes, we can create objects that represent specific instances of those classes.

Classes act as blueprints or templates, defining the attributes (data) and methods (behavior) that objects of that class will possess. Objects, on the other hand, are instances of classes that have their own state and behavior.

Java Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

Your email address will not be published. Required fields are marked *