CrimsonLogic Interview Question
Dev Leads Dev LeadsCountry: India
Interview Type: In-Person
1. Method overloading.
Having an abstract overloaded method sumBill which accepts double parameter types and let derived classes override the method. It causes less flexibility to the developers as this technique will require the changes in every derived class.
2. Encapsulation
Box the primitive type integer or double in a user defined object and the object self sufficient to know the underlying the primitive data type.
class A{
sumBill(summableObject s1, summableObject s2);
}
3. Using Java.lang.Number class, you could pass any Integer, Double etc objects..
class A{
sumBill(Number s1, Number s2);
}
Please note that Number is not a primitive.
Have sumBill accept either an interface, a class or something that exposes methods that allows 1 element to compare to the other. Example
sumBill(SummableItem a, SummableItem b)
where
interface SummableItem
{
SummableItem Sum(SummableItem other);
}
This can resolved by method Type Conversion.
public abstract class TestAbs {
public abstract void sum(double a,double b);
}public class AbsTesting extends TestAbs{
public static void main(String[] args) {
// TODO Auto-generated method stub
AbsTesting absTesting = new AbsTesting();
absTesting.sum(10.0, 20.0);
absTesting.sum(10, 20);
absTesting.sum(10L, 20L);
absTesting.sum(10f, 20f);
}
public void sum(double a,double b){
System.out.println("Sum of a + b :" +(a+ b) );
}
}
reuslt:
Sum of a + b :30.0
Sum of a + b :30.0
Sum of a + b :30.0
Sum of a + b :30.0
I guess the above solution will work,
the below code is also in the same lines
public Abstract Class Absbase<T>
{
public abtract <T> sum (T a,T b);
}
public class AbsImplementor: AbsBase
{
T _value;
public override sum <T> sum (T a,T b)
{
this._Value=a+b;
}
}
Public class Client Class
{
pubic static void main(strn[] args)
{
AbsImplementor absSum=new AbsImplementor()
System.out.println("Sum of a + b :" + absSum.sum(10,20) );
System.out.println("Sum of a + b :" + absSum.sum(10.44,20.55) );
}
}
Technically...both summable object and generics solution can be used to avoid the situation of changing parameter types.
I wonder if there is a specific design pattern name for the solution. The only thing I can say is 'code to interface' rather than to concrete principle is applicable here.
If programming language is java, then you can make use of generics.
- Anonymous November 19, 2014The input variable should be <? extends Number> instead of just int or double.
Number in java is superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.