
The complete OOP principles revolve around the object and its behaviours. These principles in Oops make it more reliable and effective. In this article, we will learn about each one of them in detail.
| Encapsulation in object oriented programming |
| public class BankAccount { private double balance; public double Balance { get { return balance; } private set { if (value >= 0) balance = value; } } public void Deposit(double amount) { if (amount > 0) Balance += amount; } public void Withdraw(double amount) { if (amount > 0 && amount <= Balance) Balance -= amount; } } |
Object Oriented Programming[/caption]
Also, check the bank and the customer example by clicking here to learn more about Abstraction in object-oriented programming.
| OOP principles: Compile time polymorphism |
| public int multiply(int a, int b) { int prod = a * b; return prod; } public int multiply(int a, int b, int c) { int prod = a * b * c; return prod; } } // Class 2 // Main class class Operation { // Main driver method public static void main(String[] args) { Product ob = new Product(); int prod1 = ob.multiply(1, 2); System.out.println( "Product of the two integer value :" + prod1); // Calling method to multiply 3 numbers int prod2 = ob.multiply(1, 2, 3); // Printing product of 3 numbers System.out.println( "Product of the three integer value:" + prod2); } } |
| OOP principles: Runtime polymorphism |
| class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Dog(); myAnimal.sound(); // Output: Dog barks myAnimal = new Cat(); myAnimal.sound(); // Output: Cat meows } } |
| OOP Principles: Inheritance |
| // Base class (or superclass) Animal class Animal { void eat() { System.out.println("Animal is eating"); } void sleep() { System.out.println("Animal is sleeping"); } } // Derived class (or subclass) Dog inheriting from Animal class Dog extends Animal { void bark() { System.out.println("Dog is barking"); } } // Derived class (or subclass) Bird inheriting from Animal class Bird extends Animal { void chirp() { System.out.println("Bird is chirping"); } } public class Main { public static void main(String[] args) { Dog myDog = new Dog(); Bird myBird = new Bird(); myDog.eat(); myDog.sleep(); myBird.eat(); myBird.sleep(); // Output: Animal is sleeping // Methods specific to subclasses myDog.bark(); // Output: Dog is barking myBird.chirp(); // Output: Bird is chirping } } |