OOP Concepts in Java.
OOP ( Object Oriented Programming )
In OOP, the two main aspects are methods and classes.
If we assume like this, class as fruit and the objects as types of fruits such as orange, grapes, apple etc.....
This clearly gives an idea that class is a blueprint or template of an object and object is an instance of a class.
class---> Fruit
objects ---> Orange, Apple, Grapes etc....
In OOP, there are main 04 concepts, they are as below;
- Encapsulation
- Inheritance
- Abstraction
- Polymorphism
The meaning of Encapsulation is to make sure that sensitive data is hidden from the users, to achieve this you must;
- declare class variables and attributes as private
- provide public get and set methods to access and update the value of a private variables
The Get method return the variable value and the Set method set the value
Example:-
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public class Main{
public static void Main(string [] args){
Person myObj = new Person();
myObj.setName(John);
System.out.println(myObj.getName());
}
}
02. Inheritance
Inheritance allows Subclass to inherit properties and methods from Superclass, this is called parent-child relationship. We group inheritance concepts into two as ;
- Subclass(child class) :- The class that inherit from an another class
- Superclass (parent class) :- The class being inherited from
To inherit from another class it uses "extend" keyword.
Example :-
class Animal {
public void eat() {
System.out.println("This animal is eating.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("The dog is barking.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
}
}
3. Abstraction
The Abstraction is the process of hiding certain details and showing only the essential details.
Abstract classes can have both abstract and regular methods
Example:-
interface Vehicle {
void drive();
}
class Car implements Vehicle {
public void drive() {
System.out.println("The car is driving.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.drive();
}
}
4. Polymorphism
Polymorphism means many forms and allows objects of different types to be accessed through the same interface. In Java, polymorphism is mainly achieved through method overriding and method overloading.
Example:-
class Animal {
public void sound() {
System.out.println("This animal makes a sound.");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
myAnimal.sound();
myDog.sound();
}
}
Comments
Post a Comment