Look at the file named, Answers.md
This repository demonstrates four fundamental principles of Object-Oriented Programming (OOP) in Java:
- Inheritance
- Encapsulation
- Polymorphism
- Abstraction
Using a simple example, looking at the properties and behaviours of different Animals.
- Animal.java: An abstract class representing a generic animal. It demonstrates encapsulation and abstraction.
- Lion.java: A class that extends
Animal
, demonstrates inheritance and polymorphism. - Bear.java: Another class that extends
Animal
, demonstrates inheritance and polymorphism. Additional method - Main.java: A driver class to run the code and demonstrate the principles in action.
To run the code, compile and execute the Main.java
file.
I will be explaining the principles using Animal.java
and Bear.java
. As Lion.java
are basically the same as
Bear.java
The Animal
class encapsulates the name and age properties by making them private and providing public getters and
setters.
In Bear
class, the growlSound property is being encapsulated within the class. With private access modifier and
public getter and setter method for it to be accessible and modified.
The Animal
class is an abstract class, because for the Animal
class will become the generic base which is going
to be
used as a concept. The concept that defines common properties/behaviours of different Animal classes. Which they can
still be
inherited and extended by subclasses.
The Bear
class extends the Animal
class, demonstrating inheritance. Bear
inherits all public and protected
members from Animal
class.
The makeSound
method in the Bear
class overrides the abstract method from the Animal
class, demonstrating
polymorphism. This make Bear
class able to be able to provide their own implementation of the method.