Skip to content

mbluemer/java_composition_over_inheritance

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 

This repository is for CSE2100 honors conversion credit.

The project: Select one of the entries from the book Effective Java. Give some working code examples to show correct and incorrect (if relevant) usage.
Provide working test code using the JUnit testing framework. Supply your own summary explanation. Submission will be in a shared git repository on UConn’s github instance. There will also be some discussion so that you can give feedback to each other on the projects.

The problem being demonstrated is using composition over inheritance.

Summary

This project is a simple demonstration of why composition is often preferred over inheritance.The specific issue shown using the JUnit test cases involves testing the age tracking of the classes BankAccountInher and BankAccountComp. By their names we can see that BankAccountComp uses composition and BankAccountInher uses inheritance, specifically from the InterestAccount class. Both accounts track their 'age' using a local private variable, one that is not part of InterestAccount.The account age is incremented every time the bank account accrues interest. The key issue that stems from the use of inheritance in this situation is when using super.accrueYears in the accrueYears function within BankAccountInher. When quickly coding this function a developer may not realize that super.accrueYears functions by calling accrue in the BankAccountInher class. This will unexpectedly trigger the accountAge to be incremented twice for every year that the account is actually accrued. While it's possible to avoid this sort of mistake it's a great example of what can happen due to inheritance. Issues like this often arise when writing up a subclass that bases its functions on the parent class and then later changing the implementation of the parent class’s functions.

About

This repository is for CSE2100 honors conversion credit.

Resources

Stars

Watchers

Forks

Releases

No releases published

Languages