Java OOPs - Step-by-Step Notes
Step 1: Class & Object
Class: A class is a blueprint/template for creating objects.
Object: An object is an instance of a class holding actual data.
Example:
class Car {
String color;
void drive() {
System.out.println("Car is driving");
Car myCar = new Car();
myCar.color = "Red";
myCar.drive();
Step 2: Constructor
Constructor: A special method that gets called when an object is created.
- Same name as class
- No return type
Example:
class Student {
String name;
Student(String n) {
name = n;
Step 3: this Keyword
Used to refer to the current object.
Java OOPs - Step-by-Step Notes
Example:
class Person {
String name;
Person(String name) {
this.name = name;
Step 4: Encapsulation
Wrapping data and code together using private fields and public methods.
Example:
class Account {
private int balance;
public void setBalance(int b) { balance = b; }
public int getBalance() { return balance; }
Step 5: Inheritance
One class inherits properties from another.
Example:
class Animal {
void sound() { System.out.println("Animal Sound"); }
class Dog extends Animal {
void bark() { System.out.println("Bark"); }
}
Java OOPs - Step-by-Step Notes
Step 6: Polymorphism
Compile-time (Overloading) and Run-time (Overriding) polymorphism.
Overloading:
int add(int a, int b) {...}
double add(double a, double b) {...}
Overriding:
class Animal { void sound() {...} }
class Cat extends Animal { void sound() {...} }
Step 7: Abstraction
Hiding implementation and showing only essentials.
Achieved via Abstract Class or Interface.
Example:
abstract class Shape {
abstract void draw();
class Circle extends Shape {
void draw() { System.out.println("Drawing Circle"); }
Summary Table
Class: Blueprint
Object: Instance of a class
Constructor: Initializes object
this: Refers to current object
Encapsulation: Data hiding
Inheritance: Reusability
Java OOPs - Step-by-Step Notes
Polymorphism: One method, multiple forms
Abstraction: Hide complexity