Java OOP Basics
OOP (Object-Oriented Programming) is the heart of Java. It organizes code into classes and objects, making programs modular, reusable, and easy to maintain. Java's four pillars — Encapsulation, Inheritance, Polymorphism, and Abstraction — form the foundation of every Java project.
What is OOP?
OOP is a programming paradigm that models real-world entities as objects. Each object has:
- State — data (fields/variables)
- Behavior — methods (functions)
Example: A Student object has state (name, age, marks) and behavior (study, takeExam, getGrade).
Class and Object
Class — The Blueprint
A class is a template that defines what an object will contain. It's not a real thing — just a design.
public class Student {
// Fields (state)
String name;
int age;
String course;
// Method (behavior)
public void display() {
System.out.println(name + " - " + age + " - " + course);
}
}
Object — The Real Thing
An object is an instance of a class. You create it with the new keyword.
public class Main {
public static void main(String[] args) {
// Create objects
Student s1 = new Student();
s1.name = "Ankit";
s1.age = 22;
s1.course = "Python";
s1.display(); // Ankit - 22 - Python
Student s2 = new Student();
s2.name = "Priya";
s2.age = 20;
s2.course = "Full Stack";
s2.display(); // Priya - 20 - Full Stack
}
}
Each object has its own copy of fields. s1 and s2 have separate names, ages, and courses.
Constructors
A constructor is a special method that runs when an object is created. It has the same name as the class and no return type.
public class Student {
String name;
int age;
// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println(name + " - " + age);
}
}
// Usage
Student s = new Student("Ankit", 22);
s.display(); // Ankit - 22
this keyword refers to the current object. Use this.name = name to differentiate the parameter from the instance variable when they have the same name.
Types of Constructors
- Default Constructor — no parameters, provided automatically if you don't define one.
- Parameterized Constructor — takes parameters to initialize fields.
- Copy Constructor — creates a new object from an existing one.
The 4 Pillars of OOP
1. Encapsulation
Hiding internal data and exposing it only through methods. Achieved by making fields private and providing public getters/setters.
public class BankAccount {
private double balance; // hidden
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
BankAccount acc = new BankAccount();
acc.deposit(1000);
System.out.println(acc.getBalance()); // 1000.0
// acc.balance = -500; // ❌ Error — balance is private
Benefit: You control how data is accessed and modified. Validation logic stays inside the class.
2. Inheritance
A class can inherit properties and methods from another class using the extends keyword.
// Parent class
public class Animal {
public void eat() {
System.out.println("Eating...");
}
}
// Child class
public class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
Dog d = new Dog();
d.eat(); // Inherited from Animal → Eating...
d.bark(); // Own method → Woof!
Types of Inheritance in Java
- Single — one parent, one child
- Multilevel — A → B → C
- Hierarchical — one parent, multiple children
- Multiple — not supported with classes (only interfaces)
super keyword
public class Animal {
public void eat() {
System.out.println("Animal eating");
}
}
public class Dog extends Animal {
@Override
public void eat() {
super.eat(); // Call parent's version
System.out.println("Dog eating");
}
}
3. Polymorphism
"Many forms" — the same method can behave differently in different contexts.
a) Compile-time (Method Overloading)
public int add(int a, int b) { return a + b; }
public int add(int a, int b, int c) { return a + b + c; }
public double add(double a, double b) { return a + b; }
b) Runtime (Method Overriding)
class Animal {
public void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Woof");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Meow");
}
}
// Polymorphism in action
Animal a;
a = new Dog();
a.sound(); // Woof
a = new Cat();
a.sound(); // Meow
The @Override annotation tells the compiler you're intentionally overriding a parent method.
4. Abstraction
Hiding implementation details and showing only essential features. Achieved using abstract classes or interfaces.
Abstract Class
abstract class Shape {
abstract double area(); // no body
public void display() {
System.out.println("This is a shape");
}
}
class Circle extends Shape {
double radius;
Circle(double r) { radius = r; }
@Override
double area() {
return Math.PI * radius * radius;
}
}
Circle c = new Circle(5);
System.out.println(c.area()); // 78.539...
Interface
An interface is a contract — a class implements it and must provide all method bodies.
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car starting");
}
public void stop() {
System.out.println("Car stopping");
}
}
Car c = new Car();
c.start(); // Car starting
c.stop(); // Car stopping
Abstract class — can have both abstract and concrete methods; single inheritance. Interface — all methods are abstract (until Java 8); multiple inheritance allowed. Use interface when you want a contract, abstract class when you want shared code.
Real-World Example — Academy System
// Parent class
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
// Child class
class Student extends Person {
String course;
Student(String name, int age, String course) {
super(name, age);
this.course = course;
}
@Override
void display() {
super.display();
System.out.println("Course: " + course);
}
}
// Another child
class Teacher extends Person {
String subject;
Teacher(String name, int age, String subject) {
super(name, age);
this.subject = subject;
}
@Override
void display() {
super.display();
System.out.println("Subject: " + subject);
}
}
public class Academy {
public static void main(String[] args) {
Person p1 = new Student("Ankit", 22, "Python");
Person p2 = new Teacher("Rahul", 35, "Full Stack");
p1.display();
System.out.println("---");
p2.display();
}
}
Access Modifiers
Modifier Class Package Subclass World
--------- ----- ------- -------- -----
public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ❌
(default) ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌
Static vs Instance Members
public class Counter {
static int totalCount = 0; // shared
int instanceCount = 0; // per-object
public Counter() {
totalCount++;
instanceCount++;
}
}
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.totalCount); // 2 (shared)
System.out.println(c1.instanceCount); // 1 (own)
System.out.println(c2.instanceCount); // 1 (own)
1. Create a BankAccount class with private balance, deposit(), withdraw(), and getBalance().
2. Create a Shape abstract class with abstract area(). Extend it with Circle and Rectangle.
3. Create a Vehicle interface with start() and stop(). Implement it in Car and Bike.
4. Demonstrate method overloading with add() for 2 args, 3 args, and doubles.
5. Show polymorphism by creating an array of Person (with Student and Teacher objects) and calling display().
Quick Revision
- Class = blueprint; Object = instance.
- Constructor — same name as class, no return type.
- Encapsulation — private fields + public getters/setters.
- Inheritance —
extends, single class inheritance only. - Polymorphism — overloading (compile-time) + overriding (runtime).
- Abstraction — abstract classes or interfaces.
this= current object;super= parent class.- Access modifiers: public, protected, default, private.
static= shared by all objects; instance = per-object.
Interview Questions
Q: What are the 4 pillars of OOP?
A: Encapsulation, Inheritance, Polymorphism, Abstraction.
Q: Difference between a class and an object?
A: A class is a blueprint or template that defines structure. An object is a real instance of that class created with new. Example: "Car" is a class; "my Honda City" is an object.
Q: Difference between method overloading and overriding?
A: Overloading — same name, different parameters, same class, resolved at compile time. Overriding — same name, same parameters, subclass redefines parent's method, resolved at runtime.
Q: Difference between abstract class and interface?
A: Abstract class can have both abstract and concrete methods, and supports single inheritance. Interface traditionally has only abstract methods (until Java 8 added default methods) and supports multiple inheritance. Use interface for contracts, abstract class for shared code.
Q: What is encapsulation and why is it important?
A: Encapsulation hides internal data using private fields and exposes it through public getters/setters. It prevents unauthorized access, enforces validation rules, and makes code easier to maintain.
Q: What does the super keyword do?
A: super refers to the parent class. Use super.method() to call the parent's version of a method, and super() to call the parent constructor.
Q: Can we instantiate an abstract class?
A: No. Abstract classes cannot be instantiated directly. You can only create objects of concrete subclasses that extend them.
Q: What is the final keyword used for in OOP?
A: final on a class — cannot be extended. On a method — cannot be overridden. On a variable — cannot be reassigned (constant).
Q: Difference between this and super?
A: this refers to the current object. super refers to the parent class object. Both are used to access fields/methods, but at different levels.
Want to Master Java?
Join our Java course in Varanasi — practical classes and career support at our Sarnath centre.