OddNumber Write a class called OddNumber which stores an int which is not a mult
ID: 3723690 • Letter: O
Question
OddNumber
Write a class called OddNumber which stores an int which is not a multiple of 2. It should have the following:
A static method boolean isOdd(int x) which returns true if x is a not a multiple of 2.
Similar constructors (but storing 1 instead of 0).
int getValue() which returns the int being stored.
EvenNumber add(OddNumber b) returns a new object representing the sum of the two stored ints.
EvenNumber sub(OddNumber b) returns a new object representing the difference between the two stored ints (this-b).
Explanation / Answer
/*Source code of the above program is given below*/
/*NOTE: If you want to change something or want in a different way, please let me know through comments; I will surely revert back to you.*/
public class OddNumber
{
//stores an int which is not a multiple of 2
private int oddNum;
//default constructor
public OddNumber()
{
this.oddNum = 1;
}
//parametric constructor
public OddNumber(int x)
{
if(isOdd(x))
this.oddNum=x;
else
this.oddNum = 1;
}
//returns true if x is a not a multiple of 2.
public static boolean isOdd(int x)
{
if(x%2==0)
return false;
else
return true;
}
//returns the int being stored
public int getValue()
{
return oddNum;
}
// returns a new object representing the sum of the two stored ints.
EvenNumber add(OddNumber b)
{
int sum=this.oddNum+b.oddNum;
EvenNumber result = new EvenNumber(sum);
return result;
}
//returns a new object representing the difference between the two stored ints
EvenNumber sub(OddNumber b)
{
int sub=this.oddNum-b.oddNum;
EvenNumber result = new EvenNumber(sub);
return result;
}
}
/*Hope this will help you. Thank you.*/
/*If this helps you, please let me know by giving a positive thumbs up. In case you have any queries, do let me know. I will revert back to you. Thank you!!*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.