I dont understand why my code in main doesnt print the 3 values, instead just th
ID: 670119 • Letter: I
Question
I dont understand why my code in main doesnt print the 3 values, instead just the memory location
System.out.format("position update1: %s",mytest.getNumbers());
public static void main(String[] args)
{
class2 testing = new class2(3,5);
class1 mytest = new class1(2,testing);
System.out.printf("position update1: %s%n",mytest.getNumbers()); // help
System.out.format("position update1: %s",mytest.numbers);//hel[
}
-------------------------------------------------------------------------------------------------------------------------------
public class class1 {
double num3;
class2 numbers;
public class1(double mynum, class2 mynum2) {
this.num3 = mynum;
double t1 = mynum2.get1();
double t2 = mynum2.get2();
this.numbers = new class2(t1, t2);
}
public class2 getNumbers() {
return numbers;
}
------------------------------------------------------
public class class2
{
double num1;
double num2;
public class2(double num1,double num2)
{
this.num1 = num1;
this.num2 = num2;
}
public double get1()
{
return num1;
}
public double get2()
{
return num2;
}
Explanation / Answer
Hi
Your code is perfectly fine but only one thing.
[ System.out.format("position update1: %s",mytest.getNumbers());
System.out.format("position update1: %s",mytest.numbers);]
in above both lines you are printing object not object value.
so when you print object : class2@19e0bgd output
All Java objects have a toString() method, which is invoked when you try and print the object.
This method is defined in the Object class (the superclass of all Java objects). The Object.toString() method returns a fairly ugly looking string, composed of the name of the class, an @ symbol and the hashcode of the object in hexadecimal. The code for this looks like:
A result such as com.foo.MyType@2f92e0f4 can therefore be explained as:
So to print something useful you have to override (toString()) method.
example.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.