Instashire

Object-Oriented Programming (OOP) in Java

Java is an Object-Oriented Programming (OOP) language that provides a structured approach to software development by organizing data and behavior into objects. OOP principles are centered around real-world modeling, making it easier to design and maintain software.

class Person {
    String name;  // Field
    int age;

    void displayInfo() {  // Method
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

Class:

A blueprint for creating objects. It defines properties (fields) and behaviors (methods).

class Person {
    String name;  // Field
    int age;

    void displayInfo() {  // Method
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

Object:

An instance of a class that contains real values.

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person();  // Object creation
        person1.name = "Alice";
        person1.age = 25;
        person1.displayInfo();  // Output: Name: Alice, Age: 25
    }
}

Advantages of OOP in Java

Core Principles of OOP in Java

Encapsulation:

class Account {
    private double balance;

    // Getter
    public double getBalance() {
        return balance;
    }

    // Setter
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.deposit(1000);
        System.out.println("Balance: " + acc.getBalance());  // Output: Balance: 1000.0
    }
}

Inheritance:

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();  // Inherited method
        dog.bark(); // Child-specific method
    }
}

Polymorphism

// Method Overloading
class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

// Method Overriding
class Animal {
    void sound() {
        System.out.println("Animal makes a sound.");
    }
}

class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Cat meows.");
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(10, 20));           // Overloading
        System.out.println(calc.add(10, 20, 30));

        Animal animal = new Cat(); // Upcasting
        animal.sound();           // Overriding
    }
}

Abstraction

// Abstract Class Example
abstract class Shape {
    abstract void draw();
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing a circle.");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape = new Circle();
        shape.draw();
    }
}

Additional Features of OOP in Java

Constructors in Java

A constructor in Java is a special method used to initialize objects. It is called automatically when an object is created. Constructors are essential for setting up an object with initial values or performing startup tasks.

Characteristics of a Constructor

Types of Constructors

//Default Constructor

class Student {
    String name;
    int age;

    // Default Constructor
    Student() {
        name = "John Doe";
        age = 18;
    }

    void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student(); // Calls default constructor
        student1.displayInfo(); // Output: Name: John Doe, Age: 18
    }
}
//Parameterized Constructor

class Student {
    String name;
    int age;

    // Parameterized Constructor
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student("Alice", 20); // Calls parameterized constructor
        student1.displayInfo(); // Output: Name: Alice, Age: 20
    }
}
//Constructor Overloading

class Student {
    String name;
    int age;

    // Default Constructor
    Student() {
        name = "Default Name";
        age = 18;
    }

    // Parameterized Constructor
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student(); // Calls default constructor
        Student student2 = new Student("Bob", 22); // Calls parameterized constructor

        student1.displayInfo(); // Output: Name: Default Name, Age: 18
        student2.displayInfo(); // Output: Name: Bob, Age: 22
    }
}

Using this() to Call Another Constructor

class Student {
    String name;
    int age;

    // Constructor with default values
    Student() {
        this("John Doe", 18); // Calls parameterized constructor
    }

    // Parameterized Constructor
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student(); // Calls default constructor
        student1.displayInfo(); // Output: Name: John Doe, Age: 18
    }
}

Key Points

//java program example//

import java.util.Scanner;

class Factorial {
    int num;
    long f;

    // Constructor to calculate factorial
    Factorial(int n) {
        num = n; // Assign input to the instance variable
        f = 1;
        for (int i = 1; i <= num; i++) {
            f = f * i;
        }
    }

    // Method to display the result
    void display() {
        System.out.println("Factorial of " + num + " is: " + f);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input number
        System.out.print("Enter a number: ");
        int no = scanner.nextInt();

        // Create Factorial object and display result
        Factorial factorial = new Factorial(no);
        factorial.display();
    }
}
//java program example//

import java.util.Scanner;

class Checker {
    int num;
    int year;

    // Constructor to initialize values and perform checks
    Checker(int n, int y) {
        num = n; // Initialize the number
        year = y; // Initialize the year
    }

    // Method to check if the number is even or odd
    void checkEvenOdd() {
        if (num % 2 == 0) {
            System.out.println(num + " is an Even number.");
        } else {
            System.out.println(num + " is an Odd number.");
        }
    }

    // Method to check if the year is a leap year
    void checkLeapYear() {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            System.out.println(year + " is a Leap Year.");
        } else {
            System.out.println(year + " is not a Leap Year.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input number
        System.out.print("Enter a number to check even/odd: ");
        int inputNum = scanner.nextInt();

        // Input year
        System.out.print("Enter a year to check leap year: ");
        int inputYear = scanner.nextInt();

        // Create Checker object and perform checks
        Checker checker = new Checker(inputNum, inputYear);
        checker.checkEvenOdd();
        checker.checkLeapYear();
    }
}