Oops in Java
Oops in Java
BY:Coding_error1
1. ENCAPSULATION
Definition:
Encapsulation is the process of wrapping variables (data) and methods (code) together as a
single unit.
Also hides the internal state of the object using private and allows access via
getters/setters.
Type:
Data Hiding
Code Example:
java
class Person {
private String name; // private variable
BY: coding_error1
2. INHERITANCE
Definition:
Inheritance allows one class to inherit fields and methods from another. Promotes code
reusability.
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance – Not supported via classes, but via interfaces
Code Examples:
Single Inheritance:
java
class Animal {
void eat() {
System.out.println("Eating...");
}
}
Multilevel Inheritance:
java
class Animal {
void eat() {
BY: coding_error1
System.out.println("Eating...");
}
}
Hierarchical Inheritance:
java
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
BY: coding_error1
3. POLYMORPHISM
Definition:
Polymorphism means “many forms”. The same method behaves differently based on the
object.
Types of Polymorphism:
Code Examples:
java
class MathOp {
int add(int a, int b) {
return a + b;
}
java
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
BY: coding_error1
System.out.println("Lion roars");
}
}
4. ABSTRACTION
Definition:
Abstraction hides internal details and shows only essential features to the user.
Types of Abstraction:
Code Examples:
Abstract Class:
java
void message() {
System.out.println("This is a shape");
}
}
BY: coding_error1
Interface:
java
interface Drawable {
void draw(); // implicitly public and abstract
}
5. CONSTRUCTORS in Java
Definition:
A constructor is a special method used to initialize objects. It has the same name as the class
and no return type.
Types of Constructors:
Default Constructor
Parameterized Constructor
Copy Constructor (custom-made in Java)
Examples:
Default Constructor:
java
class Car {
Car() {
System.out.println("Car object created!");
}
}
BY: coding_error1
}
}
Parameterized Constructor:
java
class Car {
String model;
Car(String model) {
this.model = model;
}
void showModel() {
System.out.println("Model: " + model);
}
}
java
class Car {
String model;
Car(String model) {
this.model = model;
}
void show() {
System.out.println("Model: " + model);
}
}
BY: coding_error1
6. ACCESS SPECIFIERS / MODIFIERS
Definition:
Examples:
Private:
java
class Person {
private String name = "Riya"; // only accessible in this class
java
class Car {
int speed = 100; // default access
void show() {
System.out.println("Speed: " + speed);
}
}
Protected:
BY: coding_error1
java
class Animal {
protected void sound() {
System.out.println("Animal sound");
}
}
Public:
java
BY: coding_error1