Java Class Inheritance and comparing subclass objects - java

I'm working on a homework assignment, and I'm having a really hard time wrapping my head around how to compare two of the same subclass objects.
Basically I have this superclass Magnitude:
class Magnitude {
public boolean lessThan(Magnitude m) {
}
public boolean lessThanEqualTo(Magnitude m) {
}
public boolean equalTo(Magnitude m) {
}
public boolean greaterThan(Magnitude m) {
}
public boolean notEqual(Magnitude m) {
}
}
And then I have a subclass Currency that extends Magnitude ( I am only allowed to override the lessThan() method):
class Currency extends Magnitude {
double amount;
public Currency(double amt) {
this.amount = amt;
}
#Override
public boolean lessThan(Magnitude m) {
Currency other_currency = (Currency) m;
if (this.amount < other_currency.amount) {
return true;
}
else {
return false
}
}
public void print() {
System.out.println(amount);
}
}
What exactly is the way that I should implement these methods for the super and subclass so that I can compare 2 objects of the same subclass?

You can make use of the fact that you can call lessThan() also from m and use this as the other argument.
abstract class Magnitude {
public abstract boolean lessThan(Magnitude m);
public boolean lessThanEqualTo(Magnitude m) {
return this.lessThan(m) || this.equalTo(m);
}
public boolean equalTo(Magnitude m) {
return ((!this.lessThan(m))&&(!m.lessThan(this)));
}
public boolean greaterThan(Magnitude m) {
return m.lessThen(this);
}
public boolean notEqual(Magnitude m) {
return !this.equal(m);
}
}
You then need to have
class Currency extends Magnitude {
double amount;
public Currency(double amt) {
this.amount = amt;
}
#Override
public boolean lessThan(Magnitude m) {
Currency other_currency = (Currency) m;
if (this.amount < other_currency.amount) {
return true;
}
else {
return false
}
}
public void print() {
System.out.println(amount);
}
}

Simply rewrite the methods at the subclass.
Now, if you create two instances of the subclass and compare them, it'll use the subclass method
Currency c1 = new Currency();
Currency c2 = new Currency();
c1.lessThan(c2); //will call Currency.lessThan method
To use parent's class method, use this way
c1.lessThan((Magnitude) c2);
See this form more info.

If I understand your question correctly, you want to know how to implement and override the lessThan() method in your Currency class, knowing you can only compare currencies but not magnitudes, but what you receive is a Magnitude type parameter.
In that case, you need to check if the Magnitude object you received as a paramether is actually an instance of Currency wrapped in a Magnitude class. To do that, you use the instanceof comparison operator and then cast the object to Currency:
#Override
public boolean lessThan(Magnitude m) {
if(m instanceof Currency) {
return this.amount < ((Currency)m).amount;
} else {
throw new IllegalArgumentException("Parameter is not a Currency");
}
}

Related

Looking for an implementation of an abstract method

I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
gp1.agregar(v1);
//gp1.mostrar(v1);
gp1.agregar(v2);
System.out.println(gp1.check());
GrandPrix gp2 = new GrandPrix();
gp2.agregar(vt1);
gp2.agregar(vt2);
gp2.agregar(m2);
System.out.println(gp2.check());
GrandPrix gp3 = new GrandPrix();
gp3.agregar(vt1);
gp3.agregar(vt2);
gp3.agregar(m1);
System.out.println(gp3.check());
GrandPrix gp4 = new GrandPrix();
gp4.agregar(m1);
gp4.agregar(m2);
System.out.println(gp4.check());
This is the class that is using
import java.util.ArrayList;
public class GrandPrix extends Rally{
ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();
public void agregar(Vehiculo v) {
ve.add(v);
}
public void agregar(Carro c) {
ve.add(c);
}
public void agregar(Moto m) {
ve.add(m);
}
#Override
boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
return false;
}
}
This is the class where everything goes on
public class Vehiculo {
private String Nombre;
private double velocidad_max;
private int peso;
private int comb;
public Vehiculo() {
setNombre("Anónimo");
setVel(130);
setPeso(1000);
setComb(0);
}
public Vehiculo(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
}
double rendimiento() {
return velocidad_max/peso;
}
public boolean mejor(Vehiculo otroVehiculo) {
return rendimiento()>otroVehiculo.rendimiento();
}
public String toString() {
return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
}
/**************************************
---------SET And GET Nombre------------
***************************************/
public String getNombre() {
return Nombre;
}
public void setNombre(String nuevoNombre) {
this.Nombre=nuevoNombre;
}
/**************************************
---------SET And GET velocidad_max------------
***************************************/
public double getVel() {
return velocidad_max;
}
public void setVel(double nuevaVel) {
this.velocidad_max=nuevaVel;
}
/**************************************
---------SET And GET peso------------
***************************************/
public double getPeso() {
return peso;
}
public void setPeso(int nuevoPeso) {
this.peso=nuevoPeso;
}
/**************************************
---------SET And GET comb------------
***************************************/
public int getComb() {
return comb;
}
public void setComb(int comb) {
this.comb = comb;
}
boolean esDe2Ruedas() {
return false;
}
}
This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{
private boolean sidecar;
public Moto(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(false);
}
public Moto(String string, double d, int i, int j, boolean b) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(b);
esDe2Ruedas(false);
}
public String toString() {
String str = null;
if(isSidecar())
str =super.toString()+", Moto, con sidecar";
else
str =super.toString()+", Moto";
return str;
}
public boolean isSidecar() {
return sidecar;
}
public void setSidecar(boolean sidecar) {
this.sidecar = sidecar;
}
I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.

How to add some special values to an integer type

I would like to create a Java class that besides having integer types allows to have also some Enums, that is special values, a bit like Double.
Consider the case where you want to memorize an integer 0,1,100, 1000 or a special value like "0000" or "/" or "VAR";
I suppose your class has to contain those types? as in :
public class ExampleClass
{
// Instance Variables
int intTypeVar;
String stringTypeVar;
double doubleTypeVar;
// Constructor Declaration of Class
public ExampleClass (int intTypeVar, String stringTypeVar,
double doubleTypeVar)
{
this.intTypeVar= intTypeVar;
this.stringTypeVar= stringTypeVar;
this.doubleTypeVar= doubleTypeVar;
}
You can make your own exclusive type like this:
public class State {
JUST_AN_INTEGER,
CHEESE,
SOMETHING_ELSE;
}
public final class MyInteger {
private final int value;
private final State state;
private MyInteger(int value) {
this.value = value;
this.state = State.JUST_AN_INTEGER;
}
private MyInteger(State state) {
if (state == null) {
throw new IllegalArgumentException("State must be non-null");
} else if (state == State.JUST_AN_INTEGER) {
throw new IllegalArgumentException(State.JUST_AN_INTEGER + " requires a value!");
}
this.state = state;
}
public int getValue() {
if (state != State.JUST_AN_INTEGER) {
throw new IllegalStateException("MyValue has no value, it is of state " + state");
}
return value;
}
public int getState() {
return this.state;
}
#Override
public int hashCode() {
return this.value ^ this.state.hashCode();
}
#Override
public int equals(Object o) {
if (!(o instanceof MyInteger)) {
return false;
}
MyInteger other = (MyInteger) o;
return other.state == this.state && other.value == this.value;
}
#Override
public String toString() {
if (this.state == State.JUST_AN_INTEGER) {
return String.valueOf(this.value);
}
return this.state.name();
}
}
This MyInteger can either have a normal integer value or be of one of the other states. The constructors ensure that it's only ever constructed in a consistent way (for example you wouldn't want a JUST_AN_INTEGER constructed without an explicit value and equally you wouldn't want a CHEESE state to also contain a value).
You could also implement the Number class, but that would lead to all kinds of confusing behaviour, since it doesn't act like a normal Number in many cases.

Comparing object in Java

Here is my application
public class testwithmain {
public static void main(String[]args)
{
Money m12CHF = new Money(12,"CHF");
System.out.println(m12CHF.amount());
Money m14CHF = new Money(14,"CHF");
System.out.println(m14CHF.amount());
Money expected = new Money(26,"CHF");
System.out.println("expected "+expected.amount()+expected.currency());
Money result = m12CHF.add(m14CHF);
System.out.println("result "+result.amount()+result.currency());
System.out.println(expected.equals(result));
}
}
//-------------------------
public class Money {
private int fAmount;
private String fCurrency;
public Money(int amount, String currency) {
fAmount = amount;
fCurrency = currency;
}
public int amount() {return fAmount;}
public String currency() {return fCurrency;}
public Money add(Money m) {
return new Money(amount() + m.amount(), currency());
}
}
The result is:
12
14
expected 26CHF
result 26CHF
false
Please, why i have false ?
Thank you so much.
Your Money class lacks an implementation of equals method, which is required in order for Java to know that the object representing the result of m12CHF.add(m14CHF) and the new Money(26,"CHF") represent the same thing, even though the two are distinct Java objects.
The code inside equals should follow this general template:
#Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Money)) {
return false;
}
Money other = (Money) o;
... // Your code goes here
}
#Override
public int hashCode() {
return Objects.hash(fAmount, fCurrency);
}
Your implementation needs to compare fAmount and fCurrency of your object to the values in other.fAmount and other.fCurrency. Use equals for comparison of String objects; numbers can be compared with == operators.
As Nexevis said you need to override the equals method (which is inherited from the object class)
#Override
public boolean equals(Object obj){
if(obj instanceof Money){
Money other = (Money)obj;
//now you define when two intance object of Money are equal...
}
//...
}
Why is this necessary?
Because the current equals that you are using it is the equals from the Object class. Object's equals method defines that two objects are the same when they have the same reference

Is it a good way to implement Distance with diffrent units

I was looking for some good patterns to have possibility to express distance in different units. I found Martin Fowler article about quantities and I programmed something like:
Here is Distance class ( I think it is not necessery to make it abstract ):
public class Distance {
double mValue;
DistanceUnit mUnit;
public Distance(double value, DistanceUnit unit){
this.mValue = value;
this.mUnit = unit;
}
public Distance toUnit(DistanceUnit unit){
double factor = this.mUnit.getMetresFactor()/unit.getMetresFactor();
double newValue = this.mValue * factor;
Distance distance = new Distance(newValue, unit);
return distance;
}
#Override
public String toString(){
return String.valueOf(mValue);
}
}
It looks very simple. Conversion toUnit is based on DistanceUnit method getMetresFactor. Each Unit class implements DistanceUnit interface and has method getMetresFactor() like:
public interface DistanceUnit {
double getMetresFactor();
}
public class Inch implements DistanceUnit {
#Override
public double getMetresFactor() {
return 0.0254;
}
}
public class Kilometer implements DistanceUnit {
#Override
public double getMetresFactor() {
return 1000.0;
}
}
And the usage is for example:
Distance inches = new Distance(300.0, new Inch());
Distance kilometres = inches.toUnit(new Kilometres());
So it returns the correct value.
Is it good way to store distance in this way? Maybe you know some weaknesses of this approach. Maybe is a good idea to use here a FactoryMethod pattern to construct distance based on unit shortcut like "m" for meter. I think about the amount of classes if I would have a lot of units... Is it good idea to have factory which return factor of meters based on unit name? There will be no classes for units then?
Hm, i would use enum instead of DistanceUnit classes, because there is no different instances of them.
You can set a value to enum like here
and then call enum.getValue() instead of unit.getMetresFactor().
Also it is a little bit confusing, is the mValue value in meters or in DistanceUnit's, if in meters, you must have
double factor = unit.getMetresFactor();
there
Ok and now with any convertion function support:
import java.util.HashMap;
import java.util.Map;
public abstract class MeasureConverter {
public abstract double valueToBasic(double value);
public abstract double basictoValue(double basic);
/**
*
*/
public static Map<String, MeasureConverter> converters;
public static Map<String, MeasureConverter> getConverters() {
if (converters == null) {
converters = new HashMap<String, MeasureConverter>();
converters.put("kilo", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value * 1000;
}
#Override
public double basictoValue(double basic) {
return basic / 0.001;
}
});
// taking the basic temperature value in kelvines
converters.put("kelvine", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value;
}
#Override
public double basictoValue(double basic) {
return basic;
}
});
converters.put("celsius", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value + 273.15;
}
#Override
public double basictoValue(double basic) {
return basic - 273.15;
}
});
converters.put("faren", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value * 1.8 - 459.67 ; // or whatever is there?
}
#Override
public double basictoValue(double basic) {
return (basic + 459.67 ) / 1.8;// or whatever is there?
}
});
}
return converters;
}
}
And then :
import java.util.Objects;
public class MeasurePattern {
double value;
String name;
public MeasurePattern(double value, String name) {
this.value = value;
this.name = name;
}
#Override
public String toString() {
return "MeasurePattern{" + "value=" + value + ", name=" + name + '}';
}
#Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + (int) (Double.doubleToLongBits(this.value) ^ (Double.doubleToLongBits(this.value) >>> 32));
hash = 29 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MeasurePattern other = (MeasurePattern) obj;
if (Double.doubleToLongBits(this.value) != Double.doubleToLongBits(other.value)) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
public MeasurePattern convertTo(String converter) {
MeasureConverter mycon = MeasureConverter.getConverters().get(name);
MeasureConverter hiscon = MeasureConverter.getConverters().get(converter);
double basic = mycon.valueToBasic(value);
double hisValue = hiscon.basictoValue(basic);
return new MeasurePattern(hisValue, converter);
}
public static void main(String[] args) {
//trying temperatures;
MeasurePattern temp = new MeasurePattern(10, "celsius");
MeasurePattern kelvine = temp.convertTo("kelvine");
MeasurePattern faren = kelvine.convertTo("faren");
MeasurePattern cels = faren.convertTo("celsius");
System.out.println("kelvine = " + kelvine);
System.out.println("faren = " + faren);
System.out.println("cels = " + cels);
}
}
Output:
kelvine = MeasurePattern{value=283.15, name=kelvine}
faren = MeasurePattern{value=412.67777777777775, name=faren}
cels = MeasurePattern{value=9.999999999999943, name=celsius}
You can implement it analog to java.util.concurrent.TimeUnit as an enum. E.g.
public enum DistanceUnit {
KILOMETER {
#Override
protected double conversionFactor(DistanceUnit toDistanceUnit) {
switch (toDistanceUnit) {
case KILOMETER:
return 1;
case MILE:
return 0.621371;
default:
throw new UnsupportedOperationException(toDistanceUnit + " is not supported");
}
}
},
MILE {
#Override
protected double conversionFactor(DistanceUnit toDistanceUnit) {
switch (toDistanceUnit) {
case KILOMETER:
return 1.60934;
case MILE:
return 1;
default:
throw new UnsupportedOperationException(toDistanceUnit + " is not supported");
}
}
};
public double toDistance(double value, DistanceUnit targetDistance) {
return value * conversionFactor(targetDistance);
}
protected abstract double conversionFactor(DistanceUnit toDistanceUnit);
}
change your Distance class to
public class Distance {
double mValue;
DistanceUnit mUnit;
public Distance(double value, DistanceUnit unit){
this.mValue = value;
this.mUnit = unit;
}
public Distance toUnit(DistanceUnit unit){
double newValue = mUnit.toDistance(mValue, unit);
Distance distance = new Distance(newValue, unit);
return distance;
}
#Override
public String toString(){
return String.valueOf(mValue);
}
}
and the client code will look very clear
public class Main {
public static void main(String[] args) {
Distance kilometers = new Distance(265.35, DistanceUnit.KILOMETER);
Distance miles = kilometers.toUnit(DistanceUnit.MILE);
System.out.println(miles);
}
}
will output
164.88079485000003
Java convention does not use a m(ember) prefix (but say a this. qualification), and convention is taken quite seriously in java (as opposed to C++ for instance).
toString misses the unit.
JScience offers more, the capability to calculate in different units, m/s², and so on. Your class is a nice abstraction. But in a wider context, you probably will want to have math operations, powers of units (-2 for s above).
Take a look at your own usage ideas first:
(Just garbage:)
U speedUnit = U.of(Distance::km, Time::h.up(-1));
double timeInS = U.mile(40).div(speedunit(30)).in(U.m);
I think you should use the "Strategy" pattern.
An interface:
public interface DistanceUnit {
double getDistance(int metres);
}
The Inch class:
public class Inch implements DistanceUnit {
#Override
public double getDistance(int metres) {
return meters*39; //do conversion here
}
}
The Kilometers class:
public class Kilometres implements DistanceUnit {
#Override
public double getDistance(int metres) {
return meters/1000; //do conversion here
}
}
Then:
List<DistanceUnit> distanceList = new ArrayList<>();
distanceList.add(new Inch());
distanceList.add(new Kilometres());
for (DistanceUnit item : distanceList) {
System.out.println(item.getDistance(1000));
}
If I understand you, I think it is a simple and clean solution.
You can follow this model for conversion between others units.

Abstract class error in java

I'm trying to figure out why i keep getting the error that my AM class does not override abstract method. In my teachers UML diagram it only shows that i need the equals (Object o) method in my parent radio class. Also i'm not declaring it as abstract in my abstract class.
public abstract class Radio implements Comparable
{
double currentStation;
RadioSelectionBar radioSelectionBar;
public Radio()
{
this.currentStation = getMin_Station();
}
public abstract double getMax_Station();
public abstract double getMin_Station();
public abstract double getIncrement();
public void up()
{
}
public void down()
{
}
public double getCurrentStaion()
{
return this.currentStation;
}
public void setCurrentStation(double freq)
{
this.currentStation = freq;
}
public void setStation(int buttonNumber, double station)
{
}
public double getStation(int buttonNumber)
{
return 0.0;
}
public String toString()
{
String message = ("" + currentStation);
return message;
}
public boolean equals (Object o)
{
if (o == null)
return false;
if (! (o instanceof Radio))
return false;
Radio other = (Radio) o;
return this.currentStation == other.currentStation;
}
public static void main(String[] args)
{
Radio amRadio = new AMRadio();
System.out.println(amRadio);
Radio fmRadio = new FMRadio();
System.out.println(fmRadio);
Radio xmRadio = new XMRadio();
System.out.println(xmRadio);
}
}
public class AMRadio extends Radio
{
private static final double Max_Station = 1605;
private static final double Min_Station = 535;
private static final double Increment = 10;
public AMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("AM " + this.currentStation);
return message;
}
}
You have to implement the compareTo() method, given that Radio implements the Comparable interface and a concrete implementation for this method wasn't provided in the Radio class, so you have two choices:
Implement compareTo() in all of Radio's subclasses
Or implement compareTo() in Radio
Something like this, in AMRadio:
public int compareTo(AMRadio o) {
// return the appropriate value, read the linked documentation
}
Or like this, in Radio:
public int compareTo(Radio o) {
// return the appropriate value, read the linked documentation
}

Categories