Before starting Oop principles it will be better if you understand what is constructor at first :
Introduction to Constructors
In object-oriented programming, a constructor is a special method used to initialize an object when it is created. Think of it as a setup function that gets called automatically every time you create a new object from a class.
Key Features of a Constructor:
- Same Name as the Class: A constructor has the same name as the class it belongs to.
- No Return Type: Unlike regular methods, constructors do not have a return type, not even void.
- Automatic Invocation: You don’t call the constructor directly; it gets invoked automatically when an object is created.
Code Example in Java:
Let’s take an example of a class Car. Imagine you want to create car objects and assign a name to each car when it is created. Here’s how a constructor can help:
class Car {
String name; // Property of the car
// Constructor
Car(String carName) {
name = carName; // Initialize the name property
}
// Method to display the car name
void displayCarName() {
System.out.println("Car Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of Car using the constructor
Car car1 = new Car("Tesla");
Car car2 = new Car("BMW");
// Displaying the names of the cars
car1.displayCarName(); // Output: Car Name: Tesla
car2.displayCarName(); // Output: Car Name: BMW
}
}
How Does This Work?
- When you create a Car object using new Car("Tesla"), the constructor is called automatically.
- The value "Tesla" is passed to the constructor, and it assigns this value to the name property of the Car object.
- Now, the Car object is initialized and ready to use!
Note: In my previous blog, what I called Attributes & Behaviors is called as Property & Method simultaneously . for better understanding see the previous blog post.
Now when you have understood the concept of constructor. let's deep dive in four principles of OOP :
1. Inheritance
Inheritance is one of the key principles of object-oriented programming (OOP). It allows a class (called the child class or subclass) to inherit properties and methods from another class (called the parent class or superclass).This works same as you(as a child) inherited some of the attributes and behaviour of your parents.
This helps to:
- Reuse code instead of rewriting it.
- Create a hierarchy between classes for better organization.
- Add new functionalities to an existing class without modifying it.
In simple word : Inheritance allows you to define a new class that is based on an existing class. The new class gets all the features of the parent class and can also have additional features.The extends keyword is used for inheritance in java. Subclass extends superclass
For example : Let’s say we have a class called Animal. All animals have some common features like eating or sleeping. If we create a Dog class, instead of rewriting these features, we can simply inherit them from the Animal class.
Code Example of Inheritance in Java:
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
void sleep() {
System.out.println("This animal sleeps.");
}
}
// Child class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
// Accessing methods from the parent class
myDog.eat(); // Output: This animal eats food.
myDog.sleep(); // Output: This animal sleeps.
// Accessing method from the child class
myDog.bark(); // Output: The dog barks.
}
}
Types of Inheritance
- Single Inheritance(A child class inherits from one parent class.)
- Multilevel Inheritance(A child class inherits from a parent class, and another class inherits from this child class. for example : BabyDog inherits from Dog, which inherits from Animal)
- Hierarchical Inheritance(Multiple child classes inherit from a single parent class.For example: Cat and Dog inherit from Animal.)
Note: we cannot inherit more than one class in java . While interfaces can be utilized to create behavior similar to multiple inheritance in Java.Don't get confused for now we will talk about interfaces later.
Now lets see two very important keyword in inheritance:
this Keyword:
The this keyword refers to the current object of the class. It’s primarily used to:
- Distinguish between instance variables and method parameters if they have the same name
- Call other methods of the same class.
- Pass the current object as a parameter.
Example of this:
class Car {
String name;
// Constructor
Car(String name) {
this.name = name; // 'this.name' refers to the instance variable
}
void displayCarName() {
System.out.println("Car Name: " + this.name);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Tesla");
car.displayCarName(); // Output: Car Name: Tesla
}
}
super Keyword:
he super keyword is used to refer to the parent class in a child class. It is used for:
- Calling the parent class constructor.
- Accessing parent class methods or properties that are overridden by the child class.
Example of super:
class Animal {
String name;
// Parent class constructor
Animal(String name) {
this.name = name;
}
void makeSound() {
System.out.println("This animal makes a sound.");
}
}
class Dog extends Animal {
Dog(String name) {
super(name); // Calling the parent class constructor
}
void makeSound() {
super.makeSound(); // Calling the parent class method
System.out.println("The dog barks."); // Adding its own behavior
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy");
myDog.makeSound();
// Output:
// This animal makes a sound.
// The dog barks.
}
}
Now lets start our next principle,
2. Polymorphism
The word polymorphism comes from the Greek words "poly" (many) and "morphs" (forms). In simple terms, it allows a single interface to represent different behaviors depending on the context.
For example, consider a person: they can be a student in a classroom, an employee at work, or an athlete in a sports event. Similarly, in programming, polymorphism enables the same entity (like a method or object) to behave differently in various scenarios.
Types of Polymorphism
- Compile-Time Polymorphism (Static Polymorphism) This type of polymorphism is resolved at the time of compilation. It is achieved using method overloading.
Method Overloading: When two or more methods in the same class share the same name but have different parameter lists (number, type, or order of parameters).
Key Features:
- Happens in the same class.
- Determined during compile time. Example of Method Overloading:
class Calculator {
// Method to add two numbers
int add(int a, int b) {
return a + b;
}
// Overloaded method to add three numbers
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // Output: 5
System.out.println(calc.add(2, 3, 4)); // Output: 9
}
}
- Runtime Polymorphism (Dynamic Polymorphism) This type of polymorphism is resolved during runtime. It is achieved using method overriding.
Method Overriding: When a subclass provides a specific implementation of a method already defined in its parent class.
Key Features:
- Happens between parent and child classes.
- Determined during runtime using dynamic method dispatch. Example of Method Overriding:
class Animal {
void makeSound() {
System.out.println("This animal makes a sound.");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Parent class reference, child class object
myAnimal.makeSound(); // Output: The dog barks.
}
}
Method Overloading vs. Method Overriding
Aspect | Method Overloading | Method Overriding |
---|---|---|
Defination | Same method name, different parameter lists. | Same method name, same parameter lists. |
Occurs In | The same class. | Parent-child relationship. |
Resolved When | Compile time. | Runtime. |
Return Type | Can vary. | Must be the same. |
Conclusion
In this blog, we explored two fundamental pillars of Object-Oriented Programming: Inheritance and Polymorphism. We learned how these concepts enable reusability, flexibility, and dynamic behavior in programming.
Unfortunately, I couldn’t cover the concepts of **Abstraction **and **Encapsulation **in this post. But don’t worry! These essential topics will be explained in detail in my next blog. Once it is released, the link will be updated here, so stay tuned for more!
Thank you for reading, and I hope this blog helps you better understand the fascinating world of OOP. 😊
Top comments (0)