Class and Object:
- Class: Blueprint or template for creating objects.
- Object: Instance of a class; represents a real-world entity.
java// Class definition
class Car {
// Fields (attributes)
String model; int year;
// Methods (behavior)
void start() {
// implementation
}
}
// Creating an object
Car myCar = new Car();Encapsulation:
- Bundling of data (attributes) and methods that operate on the data into a single unit (class).
- Access modifiers (
public
,private
,protected
) control access to class members.
javaclass BankAccount {
private double balance;
public void deposit(double amount){
// implementation
}
public double getBalance() {
return balance;
}
}Inheritance:
- A mechanism where a new class inherits properties and behaviors of an existing class.
extends
is used to implement inheritance.
javaclass Animal {
void eat() {
// implementation
}
}
class Dog extends Animal {
void bark() {
// implementation
}
}Polymorphism:
- Ability of a method to do different things based on the object it is acting upon.
- Achieved through method overloading and overriding.
javaclass Shape {
void draw() {// implementation}
}
class Circle extends Shape {
void draw() { // overridden implementation }
}
// Polymorphic behavior
Shape myShape = new Circle();
myShape.draw();Abstraction:
- Concept of hiding the complex implementation details and showing only essential features of an object.
- Abstract classes and interfaces are used to achieve abstraction.
javaabstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() { // implementation }
}Interface:
- A collection of abstract methods.
- Classes implement interfaces to provide specific implementations for those methods.
javainterface Printable {
void print();
}
class Document implements Printable {
public void print() { // implementation }
}Constructor:
- Special method used for initializing objects.
- It has the same name as the class and no return type.
javaclass Person {
String name;
// Constructor
public Person(String n) { name = n; }
}
// Creating an object with a constructor
Person person1 = new Person("John");Getter and Setter:
- Methods used to retrieve and update the values of private fields.
javaclass Student {
private String name;
// Getter
public String getName() { return name; }
// Setter
public void setName(String n) { name = n; }
}