There are a few essential pointers in object-oriented programming that you must understand to produce code that is easy to read and maintain. Inheritance, encapsulation, abstraction, and polymorphism are examples of these ideas. This blog article will define these words and explain how they might be applied to write more efficient code.
Object-Oriented Programming (OOPs) refers to programming languages that employ objects, as the name implies. Object-oriented programming tries to implement real-world elements in programming, such as inheritance, hiding, and so on. The primary goal of OOP is to connect the data and the functions that operate on it so that no other part of the code may access the data except that function. In this tutorial, we will go over all of the ideas of OOPs with an example.
Assume we have a bird class and are compiling a list of birds. Let's look at the OOP concepts employed in this bird's design.
Inheritance
For each bird, there is a set of predetermined qualities shared by all birds and a set of properties unique to that species. As a result, we may instinctively state that all birds share traits such as wings, legs, eyes, and so on. As a result, in the object-oriented representation of birds, we first declare a bird class with a set of characteristics that all birds share.
We must refrain from stating these standard features in every bird we build by doing so. Instead, we may inherit the bird class from all the birds we make. The following is an example of how the inheritance concept is used.
Example:
// Java program to demonstrate
// the bird class
// Implementing the bird class
public class Bird {
// Few properties which
//Define the bird
String color;
int legs;
// Few operations in which the
//bird performs
public void eat()
{
System.out.println(
"This bird has eaten");
}
public void fly()
{
System.outp.println(
"This bird is flying");
}
}
If we want to make a crow after creating the bird class, we inherit the bird, as mentioned earlier class.
// Java program to demonstrate the
// Inheritance
// Creating the Crow class which
// extends the bird class
public class Crow extends bird {
// Overriding the fly method
// which makes this Crow fly
public void fly()
{
System.out.println(
"Crow flys!!!!");
}
}
Inheritance in the Real World:
We inherit properties from the 'Human' class, such as the ability to speak, breathe, eat, and drink. We may also use automobiles as an example. The class 'Car' inherits its properties from the class 'Automobiles,' which inherits part of its properties from another class, 'Vehicles.'
Type of Inheritance in Java
Now, we will go over each type of inheritance using examples and programs.
1. Single-Level Inheritance
A single child class inherits properties from one parent class in single inheritance. In simple words, Class A is a basic class derived from Class B. It is also referred to as single-level inheritance.
Syntax:
class A
{
//methods and fields
}
Class B extends A
{
//methods and fields
Example:
//Base class
class Person
{
String name= "Atul";
public void show()
{
System.out.println("Student inheriting properties from Person");
}
}
//child class
class Student extends Person
{
// defining additional properties to the child class
String course = "Cipherschool’s Java Course";
public void show1()
{
System.out.println("I am a Student who belongs to class A");
}
public static void main(String args[])
{
Student obj = new Student();
obj.show();
obj.show1();
System.out.println("Name of student: " +obj.name);
System.out.println("Course opted by the student: " +obj.course);
}
}
Output:
Student inheriting properties from Person
I am a Student who belongs to class A
Name of student: Atul
Course opted by the student: Cipherschool's Java Course
2. Multilevel Inheritance in Java
In this sort of inheritance, the child or derived class inherits the superclass's features while also acting as a superclass for another derived class.
Example:
//Base class
class Person
{
public void show()
{
System.out.println("Student inheriting properties from Person");
}
}
class Student extends Person
{
public void show1()
{
System.out.println("I am a Student who belongs to Person class");
}
}
//child class
class EngineeringStudent extends Student
{
// defining additional properties to the child class
public void show2()
{
System.out.println("Engineering Student inheriting properties from Student");
}
}
public class MultilevelDemo
{
public static void main(String args[])
{
EngineeringStudent obj = new EngineeringStudent();
obj.show();
obj.show1();
obj.show2();
}
}
Output:
Student inheriting properties from Person
I am a Student who belongs to Person class
Engineering Student inheriting properties from student
3. Hierarchical Inheritance in Java
One class serves as a superclass (base class) for several subclasses in Hierarchical Inheritance. Several subclasses can inherit a base class's features.
Example:
//Base class
class Person
{
public void show()
{
System.out.println("I am a Person");
}
}
//child class1
class Student extends Person
{
public void show1()
{
System.out.println("I am a Student who is Person ");
}
}
//child class2
class Teacher extends Person
{
// defining additional properties to the child class
public void show2()
{
System.out.println("I am a Teacher who is a Person");
}
}
//child class3
class Doctor extends Person
{
// defining additional properties to the child class
public void show3()
{
System.out.println("I am a Doctor who is a Person");
}
}
public class HierarchicalInheritance
{
public static void main(String args[])
{
Teacher teacher = new Teacher();
Student student = new Student();
Doctor doctor = new Doctor();
student.show();
student.show1();
teacher.show2();
doctor.show3();
}
}
Output:
I am a Person
I am a Student who is Person
I am a Teacher who is a Person
I am a Doctor who is a Person
4. Multiple Inheritance in Java
One child or subclass class can have more than one base class or superclass and inherit characteristics from each parent class it inherits in Multiple Inheritance.
As previously stated, Java does not support multiple inheritances with classes. Interfaces are the only way to achieve multiple inheritances.
Example:
//base interface1
interface Moveable
{
public void run();
}
//base interface2
interface Speakable
{
public void speak();
}
//child interface inheriting two base interfaces
interface Ability extends Moveable, Speakable
{
public void show();
}
class Person implements the ability
{
@Override
public void run()
{
System.out.println("I can run !!");
}
@Override
public void speak()
{
System.out.println("I can speak !!");
}
@Override
public void show()
{
System.out.println("I am a person, I can speak and run !!");
}
}
public class MultipleInheritance
{
public static void main(String[] args)
{
Person obj = new Person();
obj.run();
obj.speak();
obj.show();
}
}
Output:
I can run !!
I can speak !!
I am a person, I can speak and run !!
5. Hybrid Inheritance in Java
It results from the combination of two or more types of inheritance. Because Java does not support multiple inheritances with classes, hybrid inheritance is likewise impossible. Only through Interfaces can we accomplish hybrid inheritance.
Example:
//base class 1
class Ability
{
public void show()
{
System.out.println("I am a person, I can speak and run !!");
}
}
//child interface 1
interface Moveable
{
public void run();
}
//child interface2
interface Speakable
{
public void speak();
}
//child class inheriting two base interfaces
class Person extends ability implements Moveable, Speakable
{
@Override
public void run()
{
System.out.println("I can run !!");
}
@Override
public void speak()
{
System.out.println("I can speak !!");
}
}
public class HybridInheritance
{
public static void main(String[] args)
{
Person obj = new Person();
obj.run();
obj.speak();
obj.show();
}
}
Output:
I can run !!
I can speak !!
I am a person, I can speak and run !!
Encapsulation
We have now established the characteristics of the bird class and the qualities that the birds' qualities, such as color, wings, and legs, can be initialized by creating a bird class object. However, if we alter the properties of the bird class using the object's reference, the attributes lose the information by which it was initially initialized.
For example, suppose we generated a crow with a black color by defining a function Object() { [native code] }; any user with an instance of the crow's object can alter this color to red or black by simply referencing to the attribute using the "this" keyword.
As a result, we enclose the properties in the methods to avoid this. These techniques are known as attribute getters and setters. Instead of referring to the property directly, the idea is to surround the initialization and retrieval of the attributes in a method. This is also advantageous because setters allow us complete control over setting the attribute's value and help us limit unwanted changes.
For example, if a crow is born with a black color, the color does not change until the crow dies. As a result, a user who is simply utilizing should not be able to change the color as he pleases. As mentioned earlier, the implementation of the getters and setters for the bird is shown below.
Example:
// Java program to demonstrate
// the bird class
// Implementing the bird class
public class Bird {
// Few properties which
// define the bird
String color;
int legs;
// Implementing the getters and
// setters for the color and legs.
public void setColor(String color)
{
this.color = color;
}
public String getColor()
{
return this.color;
}
public void setLegs(String legs)
{
this.legs = legs;
}
public String getLegs()
{
return this.legs;
}
// Few operations which the
//bird performs
public void eat()
{
System.out.println(
"This bird has eaten");
}
public void fly()
{
System.outp.println(
"This bird is flying");
}
}
Encapsulation in the Real World:
Consider the mobile phone and the mobile phone manufacturer. Assume you are a Mobile Phone Manufacturer, designed and developed a Mobile Phone design (class), and now you are manufacturing a Mobile Phone (object) for sale using machinery. When you sell your Mobile Phone, the user only learns how to use it rather than how it works.
This means that you are building a class with a function, and by generating an object (capsule) of it, you are making the functionality of your class available through that object without interfering with the original class.
Example:
TV broadcasting
A cover protects it, and we may control it with a remote, eliminating the need to open the TV and change the channel.
Everything is private except the remote, which anyone may use to operate and modify the settings on the television.
Polymorphism
Polymorphism is a combination of poly and morph, where poly means many and morphs implies shapes. Polymorphism is a programming concept that allows one interface to be used for a broad range of activities. A pigeon is intrinsically a bird in the above understanding of a bird and pigeon.
Furthermore, if the birds are further classified into several groups, such as flying birds, flightless birds, and so on, the pigeon falls into the flying bird category. Furthermore, if the animal class is subdivided into plant-eating animals and meat-eating animals, the pigeon falls back into the plant-eating animal category. As a result, polymorphism refers to the ability of the same item to take numerous forms. Polymorphism is classified into two types:
1. Compile Time Polymorphism: It is often referred to as static polymorphism. Function overloading or operator overloading is used to achieve this form of polymorphism. It happens when we declare numerous methods with various signatures, and the compiler determines which method should be performed depending on the method signatures.
2. Run-time Polymorphism: It is also referred to as Dynamic Method Dispatch. It resolves a function call to an overridden method during run-time. Method Overriding is used to achieve this form of polymorphism. When the same procedure with the same parameters is overridden in multiple contexts, the compiler is unaware of the override. It checks to see if the method exists and executes the overridden functions at run-time.
We can also upcast and downcast objects in Java. Polymorphism is also at the heart of this concept. The concept of polymorphism in Java is that the object of the bird might have the value of the pigeon since it inherits the bird's characteristics. As a result, if both objects extend each other in the following way, a parent object can also be initialized with the child properties.
Example:
class Polygon {
// method to render a shape
public void render() {
System.out.println("Rendering Polygon...");
}
}
class Square extends Polygon {
// renders Square
public void render() {
System.out.println("Rendering Square...");
}
}
class Circle extends Polygon {
// renders circle
public void render() {
System.out.println("Rendering Circle...");
}
}
class Main {
public static void main(String[] args) {
// create an object of Square
Square s1 = new Square();
s1.render();
// create an object of Circle
Circle c1 = new Circle();
c1.render();
}
}
Polymorphism in the Real World:
Example 1:
A teacher acts toward a student.
A teacher's attitude towards his or her superiors.
In this case, a teacher is an object, but attitude varies depending on the situation.
Example 2:
A person acts like a SON at home while acting like an EMPLOYEE at work.
Example 3: Your cell phone has one name but several different forms.
As the phone
As the camera
In the capacity of an MP3 player
Because of radio
Abstraction
Abstraction is concealing an object's technical details so that it can be utilized without understanding how it works. This enables you to write code that is simple to use and maintain. For example, you could create a Vehicle class with methods like drive and stop. The user is unaware of how these methods work, so they can invoke them and assume they will function as intended.
Abstraction is crucial because it enables you to write code that is simple to use and comprehend. Abstraction allows the user to utilize your code without understanding how it works in detail.
The following are the reasons why abstraction is seen as an important concept:
It simplifies the process of viewing things.
Reduces code duplication and improves reusability.
As only vital details are supplied to the user, it helps to increase an application's or program's security.
Example:
abstract class Language {
// method of abstract class
public void display() {
System.out.println("This is Java Programming");
}
}
class Main extends Language {
public static void main(String[] args) {
// create an object of Main
Main obj = new Main();
// access method of abstract class
// using object of Main class
obj.display();
}
}
Output:
This is Java programming
Example from the Real World:
Consider the following example:
You have a phone and can dial a number using the keypad buttons. You need to learn how these work within. This is known as abstraction. You have all of the information required to call a number. But not its interior mobile workings.
Conclusion
Finally, Object-Oriented Programming (OOP) is a robust paradigm enabling efficient and modular development. Abstraction, encapsulation, inheritance, and polymorphism are four essential ideas of OOP.
Developers can use abstraction to construct abstract classes or interfaces that define common behaviors without specifying implementation specifics. Classes can implement or modify these abstractions to offer their implementation, allowing for code reusability and flexibility. Abstraction encourages the separation of concerns and aids in developing scalable and maintainable programming.
Encapsulation emphasizes shielding an object's internal details and exposing only what is required via well-defined interfaces. This safeguards the data's integrity and gives you more control over access and alteration. Encapsulation improves code maintainability and lowers the likelihood of unwanted changes or problems.
Inheritance allows classes to be created that inherit properties and behaviors from a parent class, often known as a superclass or base class. This enables code duplication and hierarchically promotes code organization. Because common characteristics can be declared in a superclass and inherited by several subclasses, inheritance enhances code extensibility and eliminates redundancy.
Thanks to polymorphism, objects of different classes can be considered objects of the same type. Because objects can be interchanged without knowing their precise kinds, this enhances code flexibility and extension. Polymorphism encourages the usage of interfaces and abstract classes to specify common behaviors and increases code modularity.
To summarize, the essential concepts of OOP are abstraction, encapsulation, inheritance, and polymorphism, which enable developers to design efficient, modular, and maintainable software systems. Understanding and implementing these concepts can significantly enhance code quality, reusability, and flexibility, resulting in more resilient and scalable software programs.
You Can Also Learn This Courses From Our Website
Also Read: Java Class and Objects (With Example)
Comentários