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
- Modularity: Code is organized into classes, making it easier to manage.
- Reusability: Code reuse is achieved through inheritance and modular design.
- Security: Encapsulation ensures sensitive data is protected.
- Flexibility: Polymorphism allows dynamic behavior.
- Maintainability: Easier to debug and modify.
Core Principles of OOP in Java
Encapsulation:
- Wrapping data (fields) and methods into a single unit (class).
- Access modifiers like private, protected, and public are used to restrict direct access to fields.
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:
- Enables one class (child) to inherit fields and methods from another class (parent).
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
- The ability of a method or object to behave in multiple ways.
- Compile-Time Polymorphism (Method Overloading).
- Run-Time Polymorphism (Method Overriding).
// 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
- Hides implementation details and shows only the functionality.
- Abstract Classes.
- Interfaces
// 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
- Access Modifiers: Control the visibility of fields, methods, and classes (public, private, protected, default).
- Constructors: Special methods used to initialize objects.
- Interfaces: Define methods that a class must implement, ensuring multiple inheritance.
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
- The name of the constructor must match the class name.
- Constructors do not have a return type (not even void).
- They are called automatically when an object is created.
- If no constructor is explicitly defined, Java provides a default constructor.
- Constructors can be overloaded (multiple constructors with different parameter lists).
Types of Constructors
- Default Constructor: A constructor with no parameters. Provided by Java if no other constructor is defined.
- Parameterized Constructor: A constructor with parameters to initialize an object with specific values.
- No-Argument Constructor: A user-defined constructor without parameters.
//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
- A constructor cannot be static, abstract, or final.
- If a class has no constructor, the compiler provides a default constructor.
- this is used to refer to the current instance, while this() calls another constructor in the same class.
- Constructors do not support return statements explicitly, as they don't return values.
//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();
}
}