188k views
1 vote
State and explain three advantages of object-oriented programming. Give an example for each advantage in a Java program.

a) Encapsulation: Example - BankAccount class
b) Inheritance: Example - Animal hierarchy
c) Polymorphism: Example - Shape interface

1 Answer

1 vote

Final answer:

Advantages of OOP include Encapsulation, which bundles data and methods; Inheritance, which allows classes to derive attributes and behaviors from other classes; and Polymorphism, which lets objects be interfaced in a general way while having specific underlying implementations.

Step-by-step explanation:

There are several advantages of object-oriented programming (OOP), and we'll discuss three key ones: Encapsulation, Inheritance, and Polymorphism, each with a Java program example.

  • Encapsulation: This principle refers to the bundling of data with the methods that operate on that data. It enables us to hide the object’s actual representation by restricting access to some of the object's components. For example, the BankAccount class may have private fields like ‘balance’ and public methods to deposit or withdraw money, preventing direct access to its balance.
  • Inheritance: It allows a new class to inherit properties and methods from an existing class. Consider a basic Animal class with properties like ‘age’ and ‘weight’, and methods such as ‘eat’ and ‘sleep’. A ‘Dog’ class could extend the Animal class, inheriting its features, and also add unique methods like ‘bark’.
  • Polymorphism: This concept allows objects to be treated as instances of their parent class rather than their actual class. In the case of a Shape interface, this could mean having different classes like Circle, Square, and Triangle that all implement a method called ‘draw’, allowing each shape to be drawn differently but accessed through the same interface.

User SerenityNow
by
7.5k points