Question
package Learning; public class Number { private int num; public Number(int num) { this.num = num; } public static Number addNumbers(Number n1, Number n2) {
package Learning;
public class Number { private int num; public Number(int num) { this.num = num; } public static Number addNumbers(Number n1, Number n2) { return new Number(n1.num + n2.num); } public Number addNumbers(Number n) { return new Number(this.num + n.num); } public static void main(String []args) { Number num1 = new Number(10); Number num2 = new Number(20); //ans1 should be 30 Number ans1 = Number.addNumbers(num1, num2); // ans2 should be 30 Number ans2 = num1.addNumbers(num2); } }
class NumberAlternate { private int num; public NumberAlternate(int num) { this.num = num; } public static Number addNumbers(NumberAlternate n1, NumberAlternate n2) { return new Number(n1.num + n2.num); } public void addNumbers(NumberAlternate n) { this.num = this.num + n.num; } public static void main(String []args) { NumberAlternate num1 = new NumberAlternate(10); NumberAlternate num2 = new NumberAlternate(20); // num1 should be 30 num1.addNumbers(num2); } }
6. Part One: Define a class for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, 1/2, 3/4, 64/2, and so forth are all rational numbers. (By 1 /2 and so forth, we mean the everyday meaning of the fraction, not the integer division this expression would produce in a Java program.) Represent rational numbers as two values of type int, one for the numerator and one for the denominator. Your class should have two instance variables of type int. Call the class Rational. Include a constructor with two arguments that can be used to set the instance variables of an object to any values Also include a constructor that has only a single parameter of type int; call this single parameter wholeNumber and define the constructor so that the object will be initialized to the rational number wholeNumber/1. Also include a no-argument constructor that initializes an object to 0 (that is, to 0/1). Note that the numeratorStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started