0
upcasting and downcasting
I am having the following method: //Number is an abstract class //I am passing an object as a 1.argument and the 2nd argument is the instanzvariable itself public Number addition(Number n) { Realnumb r=(Realnumb)n;//downcasting Number n=new Realnumb(a+r.a); } public String toString() { } Main method: Number n1=new Realnumb(3.0); Number n2=new Realnumb(5.0); System.out.println(n1.addition(n2)); The result should be 8.0. My question is how to call the "toString" method in the method "addition"? As I am having a method of type "Number", what should be the return value?
5 Réponses
0
Every object has a toString() method. That's why you can print every object.
System.out.println(anyObject) -> calls toString() so you don't need to write System.out.println(anyObject.toString());
Your class RealNumb need to override toString().
public class RealNumb{
private Number n;
@Override
public String toString{
return n.toString();
}
}
You can also have a look into this code:
https://code.sololearn.com/cK2H7CdVEq45/?ref=app
0
https://code.sololearn.com/cF9J5D55GT94/?ref=app
0
Can you please check my Code? I am getting an error "String cannot be converted to Realnumber".
0
The problem is here:
public Realnumber addition(Realnumber s)
{
Realnumber p=new Realnumber (r+s.r);
// ERROR:String cannot be converted to String
return toString(p);
}
you need to return p.
toString() returns a String
0
Preet
Or else try like this
for your requirement,
Change addition and toString function return types to double.
and return double value directly from toString function.