Object-Oriented Programming in Java
Classes and Objects
Module II: Classes and Objects. This module explains how Java organizes programs using classes, objects, constructors, access control, methods, and common built-in classes. These concepts form the core of object-oriented programming.
Object-Oriented Programming Basics
Java is built around OOP principles. The key ideas are:
- Encapsulation – grouping data and methods inside a class
- Abstraction – exposing only essential features to users
- Inheritance – reusing and extending existing classes
- Polymorphism – performing actions in different ways
A class defines structure and behavior. An object is a runtime instance of the class.
Classes and Object Creation
A class contains fields (data) and methods (operations). Objects are created using the new keyword.
class Student {
int roll;
String name;
void show() {
System.out.println(roll + " - " + name);
}
}
Student s = new Student();
s.roll = 101;
s.name = "Pushkar";
s.show();Diagram: class-object-diagram.png
Constructors and Finalizer
A constructor initializes an object at creation. It has no return type, not even void. Java supports constructor overloading.
class Point {
int x, y;
Point() { // default constructor
x = 0; y = 0;
}
Point(int x, int y) { // parameterized constructor
this.x = x;
this.y = y;
}
}
Point p1 = new Point();
Point p2 = new Point(5, 8);Java no longer recommends using finalizers. Modern Java uses try-with-resources and garbage collection.
Visibility and Access Modifiers
Java provides four levels of access control:
- public – accessible everywhere
- private – accessible only inside class
- protected – class + subclasses + same package
- default – class + same package
class Employee {
private int id;
public String name;
public void setId(int id) { // encapsulation
this.id = id;
}
public int getId() {
return id;
}
}Methods and the this Reference
Methods operate on object data. The this keyword refers to the current object and resolves naming conflicts.
class Box {
private int side;
Box(int side) {
this.side = side; // resolves shadowing
}
int area() {
return side * side;
}
}Useful Built-in Classes (String, Character, StringBuffer)
Java provides several commonly used classes for text processing.
- String – immutable text
- Character – wrapper for char type
- StringBuffer – mutable and thread-safe
String name = "Pushkar";
String upper = name.toUpperCase();
Character ch = 'A';
boolean isDigit = Character.isDigit('5');
StringBuffer sb = new StringBuffer("open");
sb.append("CSE"); // openCSEDiagram: string-immutability.png