SLC S22 Week3 || Inheritance and Polymorphism in JAVA

Inheritance and Polymorphism in JAVA.png

Created by @kouba01 using Canva & PhotoFilter

Hello Steemians

Welcome to the third week of the Steemit Learning Challenge Season 22, where we continue diving into object-oriented programming (OOP) with Java. This week, our focus is on two advanced and crucial OOP concepts: Inheritance and Polymorphism. These principles are the cornerstone of designing reusable, scalable, and maintainable software.

In this week’s session, you will explore the relationships between classes, understand the concept of generalization and specialization, and learn how to redefine and overload methods for creating dynamic behaviors in Java applications. By applying these concepts, you’ll be equipped to build flexible software systems where objects interact seamlessly.

Let’s embark on this journey to deepen your understanding of OOP principles and create applications that reflect real-world interactions more effectively!


1. Relationship of Inheritance Between Classes

The concept of inheritance specifies a specialization/generalization relationship between classes (e.g., Document: Book, Magazine, … | Person: Student, Employee, …).
When a class A inherits from a class B:

  • A possesses all characteristics of B, plus those specific to A.
  • A is a specialization of B (A is a specific case).
  • B is a generalization of A (B is a general case).
  • A is called the derived class (child or subclass).
  • B is called the base class (parent or superclass).
  • Any object instantiated from A is also considered an object of type B.
  • An object instantiated from B is not necessarily an object of type A.
  • A class can inherit from multiple classes: multiple inheritance.
  • A base class can be inherited by multiple classes.
    Inheritance minimizes code writing (via reuse) and supports extension.

1.1. Inheritance in Java

  • The Object class is the parent of all classes in Java (even without explicitly mentioning it). Object only includes methods and is defined in the java.lang package of the Java API.
  • Every object is implicitly of type Object.
  • Multiple inheritance is prohibited in Java (it is possible with interfaces).

image.png

In Java, inheritance is a form of extending classes, using the keyword extends.
image.png

  • An object reference of type B can reference an object of type A, but the reverse is not true.
    Example:

image.png

1.2. Constructor of the Derived Class

  • The constructor of the base class is called by the constructor of the derived class when the latter uses super().
  • The number of parameters in super() identifies which constructor to call in the parent class.
  • The super() statement must be the first line in the constructor of the child class.
  • If super() is not explicitly called in the derived class's constructor, Java implicitly calls the default constructor of the base class.
    Example:

image.png

During the construction of a derived instance, the construction operations of the parent class are called successively:

PointColore pc = new PointColore(1, 2, "black");
// Calls the constructor of Point, then the constructor of PointColore

Remarks:

  • If both the parent and child classes lack constructors, the default constructor of the child class calls the default constructor of the base class.
  • If the child class has no constructor, its default constructor tries to call a default constructor (without arguments) of the base class. If such a constructor does not exist, a compilation error occurs.

1.3. Accessing Inherited Members with protected

  • The protected access modifier can be used in the base class.
  • Attributes and methods declared as protected in the base class are accessible (usable) by derived classes. However, this access remains restricted for other classes not derived from the base class.
    Example:

image.png

Remarks:

  • When the attributes abs and ord of the Point class are declared as protected, they are also considered attributes of the PointColore class. They can be accessed via super or this (super.abs or this.abs yield the same result).
  • If an attribute abs is declared in PointColore, then this.abs refers to PointColore’s attribute, while super.abs refers to Point’s attribute.

Example:

image.png

In this example, displaying all attributes of a PointColore must involve calling the display() method of Point and displayColor() of PointColore.
The display() method of Point is partially useful for PointColore. Hence, a method void display() can be added to the PointColore class, replacing the one from Point. This is called method overriding.


2. Overriding Inherited Methods

  • An inherited method can be overridden if its initial version is not suitable for the derived class.
  • Overriding consists of retaining the method signature (same name, parameter count, types, and order, same return type) while proposing a different implementation.

When overriding a method, the old version (from the base class) can still be invoked using super.method_name(), wherever deemed appropriate in the new code.

  • If an inherited method is overridden, only the new version becomes part of the derived class description.
    Example:

image.png


3. Final Classes and Methods

  • Java allows inheritance restriction for a class by declaring it with the final changer.
    Example:

image.png

  • Java allows preventing the overriding of an inherited method by declaring it as final.
    Example:

image.png
image.png


4. Method Overloading and Inheritance

  • Overloading refers to defining multiple methods within the same class with the same name but differing in parameters (type, order, or number) or return type.
    Example:

image.png

  • In Java, a derived class can overload a method from an ancestor class.
    Example:

image.png


5. Object References in Inheritance

  • A reference of a base class can point to an object of a derived class.
  • Casting can be used to convert a reference of a base class type to a derived class type (for an object of the derived class).
    Example:

image.png

An object of the base class type can store a reference to a derived class object. However, the reverse is not allowed without casting.


6. Polymorphism

6.1. Polymorphic Methods

  • A polymorphic method is a method declared in a superclass and overridden by a subclass.
  • Polymorphic methods allow performing similar operations on objects of different types.
  • Methods declared final cannot be overridden and are therefore not polymorphic.

6.2. Definition of Polymorphism

  • Polymorphism involves invoking methods without knowing the specific nature of the object.
  • The call is made via a reference of the same type as the object or its base class.
    A dynamic mechanism determines, at runtime, which method to invoke depending on the object's type. Polymorphism supports application extensibility.
    Example:

image.png


7. The Superclass Object

  • The Object class is the implicit parent of all simple classes.
  • A variable of type Object can reference an object of any type.
  • The Object class has some methods that can either be used as-is or overridden. The most important ones are toString() and equals().
  • The toString() method of Object provides a string containing the class name and the object's address in hexadecimal.
  • The equals() method of Object compares the memory addresses of two objects.

Homework :

Task 1: (1 point)

Understanding Inheritance:

Write a Java program that creates a Person class with attributes name and age. Then, create a Student class that inherits from Person and adds the attribute studentId. Demonstrate how to create objects of both classes and display their details.

Task 2: (0.75 point)

Method Overloading:

Create a Shape class with overloaded methods area() to calculate the area of different shapes (circle, rectangle, and triangle) based on the provided parameters.

Task 3: (0.75 point)

Method Overriding:

Develop a Bank class with a method getInterestRate(). Create two derived classes SavingsBank and CurrentBank that override the getInterestRate() method to return specific rates. Write a program to display the interest rates for both types of banks.

Task 4: (1 point)

Polymorphism in Action:

Create a class hierarchy with a base class Vehicle and derived classes Bike and Truck. Implement a method startEngine() in the base class and override it in the derived classes to display specific messages. Use polymorphism to call the methods through a base class reference.

Task 5: (1.5 points)

Real-world Example:

Build a Library Management System that uses inheritance and polymorphism. Create a base class Item with attributes id, title, and isAvailable. Extend it into derived classes Book and Magazine with additional attributes. Implement polymorphic methods to borrow and return items, and display their details.

Task 6: (2 points)

Employee Management System:

An organization employs three types of workers: contractual employees, permanent employees, and hourly workers. The following data is tracked:

  • Contractual employees: receive a fixed monthly salary.
  • Permanent employees: receive a base salary plus a performance bonus.
  • Hourly workers: paid based on the number of hours worked and the hourly rate.

Tasks:

  1. Design a class hierarchy to represent the relationship between Employee, HourlyWorker, ContractualEmployee, and PermanentEmployee. Indicate attributes and methods.
  2. Define the base class Employee with attributes such as name, CIN, address, and salary, and a method display().
  3. Define the derived classes to include specific attributes for salary calculation, a calculateSalary() method, and a display() method.
  4. In the main program, create a vector to hold three employees of different types and display their details.

Task 7: (1 points)

Understanding Class Relationships:

Given the following class definitions, analyze whether the instructions 1 to 8 in the main method are valid. If invalid, specify whether the error occurs at compilation or runtime.

class Test {
    public static void main(String args[]) {
        C1 o1 = new C1();
        C1 o2 = new C11();
        C111 o3 = new C111();
        C11 o4 = new C111();
        C1 o5 = new C111();

        o1 = o2;  // Instruction 1
        o1 = o3;  // Instruction 2
        o3 = o1;  // Instruction 3
        o4 = o5;  // Instruction 4
        o3 = (C111) o1; // Instruction 5
        o4 = (C11) o5;  // Instruction 6
        o4 = (C111) o2; // Instruction 7
        o3 = (C11) o5;  // Instruction 8
    }
}
class C1 {}
class C11 extends C1 {}
class C111 extends C11 {}

Task 8: (2 points)

Geometric Inheritance:

  1. Create a Point class with attributes x (abscissa) and y (ordinate). Include constructors Point() and Point(x, y). Add getters, setters, and a toString() method.
  2. Create a Rectangle class inheriting from Point with attributes length and width. Include constructors Rectangle() and Rectangle(x, y, length, width). Add getters, setters, and methods area() (calculate the area) and toString() (override).
  3. Create a Parallelogram class inheriting from Rectangle with an additional attribute height. Include constructors Parallelogram() and Parallelogram(x, y, length, width, height). Add getters, setters, and methods area() (override), volume(), and toString() (override).
  4. Write a test class to demonstrate the functionalities of all three classes.

Contest Guidelines

  • Post Format:

  • Rules:

    • Posts must be #steemexclusive.
    • Avoid plagiarism and AI-generated content.
    • Include original or copyright-free images with proper attribution.
    • Submission period: Monday, December 30, 2024, 00:00 UTC - Sunday, January 5, 2025, 23:59 UTC.

Rewards

SC01/SC02 would be checking on the entire 15 participating Teaching Teams and Challengers and upvoting outstanding content. Upvote is not guaranteed for all articles. Kindly take note.

At the end of the week, we would nominate the top 4 users who had performed well in the contest and would be eligible for votes from SC01/SC02.

Important Notice: The selection of the four would be based solely on the quality of their post. Number of comments is no longer a factor to be considered.


Best Regards,
Dynamic Devs Team

Sort:  

1000010446.png
Congratulations 👏🎉.

Thank you for the nomination.

1000010553.png

Sir, there is a whole post of nomination on my blog, I just commented to you .You can see my post by going there.

Congratulations, your post has been upvoted by @scilwa, which is a curating account for @R2cornell's Discord Community. We can also be found on our hive community & peakd as well as on my Discord Server

Manually curated by @ abiga554
r2cornell_curation_banner.png

Felicitaciones, su publication ha sido votado por @scilwa. También puedo ser encontrado en nuestra comunidad de colmena y Peakd así como en mi servidor de discordia

"For the programming task, this does not have critical significance, but I wanted to clarify: is this about a 2D shape (Parallelogram), or a 3D shape (Parallelepiped, Cube, Hexahedron)? Since the task involves calculating volume, it is more likely referring to a 3D shape (solid), specifically a Parallelepiped."

Coin Marketplace

STEEM 0.25
TRX 0.27
JST 0.041
BTC 98535.63
ETH 3620.18
SBD 1.60