OOP in Java
Classes, objects, constructors, inheritance, method overriding, and polymorphism in Java.
What You Will Learn in OOP in Java
Object-Oriented Programming in Java organises code as objects (instances of classes) that encapsulate data and behaviour, supporting inheritance, polymorphism, and abstraction.
- Four pillars: Encapsulation, Inheritance, Polymorphism, Abstraction.
- Class = blueprint; Object = instance with actual memory allocation.
- Constructor: special method with same name as class, no return type, initialises objects.
- Inheritance: `extends` keyword; Java supports single class inheritance, multiple interface inheritance.
- Polymorphism: compile-time (method overloading) and runtime (method overriding).
- `super` refers to parent class; `this` refers to current instance.
Syntax
class Parent {
void display() { System.out.println("Parent"); }
}
class Child extends Parent {
@Override
void display() { System.out.println("Child"); } // runtime polymorphism
void display(String msg) { System.out.println(msg); } // overloading
}Complete Code Example
class Animal {
String name;
Animal(String name) { this.name = name; }
void sound() { System.out.println(name + " makes a sound"); }
}
class Dog extends Animal {
Dog(String name) { super(name); }
@Override
void sound() { System.out.println(name + " barks"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog("Rex"); // upcasting
a.sound(); // Output: Rex barks (runtime polymorphism)
}
}Example
A `Dog` class extending `Animal` and overriding `sound()` demonstrates runtime polymorphism.
Expected Exam Questions — OOP in Java
Q1.What is encapsulation? How is it achieved in Java?
Q2.What is the difference between method overloading and overriding?
Q3.What is an abstract class? How does it differ from an interface?
Q4.What is the difference between `IS-A` and `HAS-A` relationships?
Q5.Can a constructor be inherited in Java?
🔘 MCQ Practice — OOP in Java
MCQ 1.Which OOP concept is demonstrated when the same method behaves differently in different objects?
✓ Correct Answer: Polymorphism
MCQ 2.A class cannot extend more than one class in Java. This is a limitation of:
✓ Correct Answer: Multiple Inheritance
MCQ 3.Which keyword is used to call a parent class constructor?
✓ Correct Answer: super()
Download OOP in Java PDF Notes
Get the complete OOP in Java notes as a PDF — free for enrolled students, or browse our public study materials library.