0% found this document useful (0 votes)
5 views2 pages

Java Fraction Class Implementation

The document defines a Fraction class with private fields for the numerator and denominator. It includes constructors to initialize fractions with default or specified values. Methods are provided to get/set the numerator and denominator, add and multiply fractions, convert to string representations, and track the total number of fractions created.

Uploaded by

Cream Puff
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Java Fraction Class Implementation

The document defines a Fraction class with private fields for the numerator and denominator. It includes constructors to initialize fractions with default or specified values. Methods are provided to get/set the numerator and denominator, add and multiply fractions, convert to string representations, and track the total number of fractions created.

Uploaded by

Cream Puff
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Answer & Explanation

Solved by verified expert


Rated Helpful
class Fraction {
private int numerator;
private int denominator;
private static int numFractions = 0;
public Fraction(){
numerator = 1;
denominator = 1;
numFractions++;
}
public Fraction(int n, int d){
if(n>0){
numerator = n;
}
else{
n=1;
}
if(d>0){
denominator = d;
}
else{
d= 1;
}
numFractions++;
}
public int getNumerator(){
return numerator;
}
public int getDenominator(){
return denominator;
}
static int getNumFractions(){
return numFractions;
}
public String toString(){
return [Link]("%d/%d",numerator,denominator);
}
public String mixedNumber(){
if(numerator < denominator){
return toString();
}
if(numerator%denominator == 0){
return [Link]("%d",numerator/denominator);
}
return [Link]("%d %d/%d",numerator/denominator, numerator%denominator,
denominator);
}
public void setNumerator(int n){
if(n>0){
numerator = n;
}
}
void setDenominator(int d){
if(d>0){
denominator = d;
}
}
void add(int n, int d){
if(n>0 && d>0){
int currNumerator = numerator;
int currDenominator = denominator;
numerator = (currNumerator*d) + (n*currDenominator);
denominator = (currDenominator*d);
}
}
void add(Fraction other){
int currNumerator = numerator;
int currDenominator = denominator;
numerator = (currNumerator*[Link]()) +
([Link]()*currDenominator);
denominator = (currDenominator*[Link]());
}
void multiply(int n, int d){
if(n>0 && d>0){
numerator = numerator * n;
denominator = denominator *d;
}
}
void multiply(Fraction other){
numerator = numerator * [Link]();
denominator = denominator * [Link]();
}
}
Step-by-step explanation
I have written the code.
Can you please test this code with the inputs that are given.
If you face any issue, please let me know in comments. I will assist you fully.
Have a nice day!
Thank you!

Common questions

Powered by AI

Encapsulation in the Fraction class is demonstrated by the use of private visibility modifiers for data fields such as numerator and denominator, which restricts direct access from outside the class. Public methods like getNumerator() and getDenominator() provide controlled access to the fields, ensuring data integrity and validation. The class utilizes private setters and manipulates fields internally to maintain encapsulation, though it lacks external input validation as protected by the methods themselves .

The design of the Fraction class adheres to object-oriented principles through encapsulation, where private data fields are accessed via public methods, promoting data hiding and integrity. It demonstrates abstraction by providing clear interfaces for arithmetic operations without exposing underlying implementation details. Inheritance isn't immediately apparent within the given class, but the structure is suitable for extension through subclassing or implementing interfaces that would integrate smoothly with other classes. Such a modular design enables easy integration into larger systems that manage complex mathematical computations or data processing tasks .

The mixedNumber method enhances usability by converting improper fractions into mixed numbers or whole numbers, as appropriate. This not only improves human readability but also facilitates mathematical computations that require whole number representation. The method returns a whole number when the numerator modulo the denominator equals zero, indicating that the fraction is a whole number rather than an improper fraction .

The add method that takes integers as parameters (int n, int d) performs an addition of the current fraction with another fraction defined by the integers n and d, adjusting the current fraction's numerator and denominator to the resulting sum . The add method that accepts another Fraction object achieves similar functionality but enables adding a pre-existing Fraction instance, which can simplify operations when already working with Fraction objects. This promotes code flexibility and reuse, accommodating both creation of new fractions on-the-fly and operations on existing ones .

The constructors of the Fraction class ensure that both the numerator and denominator are positive by checking the conditions (n>0) for the numerator and (d>0) for the denominator during initialization. If the provided values do not meet these conditions, the default value of 1 is assigned. This behavior ensures no negative fractions are created and prevents mathematical inaccuracies from positive or negative zero values .

The multiply method with integer parameters (int n, int d) is efficient for scaling the current fraction by constant integer values, updating both the numerator and denominator through simple arithmetic multiplication . The method that multiplies using another Fraction object allows for flexible operations directly between fractions without needing explicit conversion or manipulation of integers, enhancing operational versatility . However, limitations arise in error handling; if improper inputs are provided or overflow occurs due to large numbers, the method does not address these issues directly, potentially leading to unhandled exceptions or incorrect results .

The setNumerator and setDenominator methods in the Fraction class check that inputs are greater than zero before assignment, leaving other values unchanged. This can cause silent failures or unexpected behavior if invalid values are provided, as no feedback or error is communicated to the user. Improvements could include throwing exceptions for invalid inputs, logging warning messages, or employing a standard default assignment strategy to enhance usability and debugging processes .

Method overloading in the Fraction class is demonstrated by having both add and multiply methods that accept different parameter types—either integers or another Fraction object. This enables users to perform arithmetic operations with both simple numeric values and complex Fraction objects without needing additional conversion processes. The overloaded methods facilitate flexible interactions, making the class more versatile and user-friendly by accommodating a variety of operational contexts .

The numFractions variable is a static integer that keeps track of the number of Fraction instances created. It is incremented in each constructor, ensuring that it reflects the total number of fraction objects instantiated. This functionality can be useful for monitoring or debugging purposes, providing a count of how many fraction objects exist at any given time .

The toString method is overridden in the Fraction class to provide a more intuitive and human-readable string representation of fraction objects. This method returns the fraction in a conventional numerical format (e.g., 'numerator/denominator'), making it easier for users to comprehend and utilize fractions in outputs and logs. This avoids default Java object string outputs that include object hashtags and memory reference details, which aren't typically useful for end-users dealing with mathematical entities .

You might also like