0

I'm taking those first steps from python to java and here is my first of many Java questions do doubt.

When printing via a shortened print method, I'm running into a problem with the return value from a inherited class. I'm sure it's something simple about Java I don't get yet. I'm also trying to convert any integers the println method receives to a string with .tostring(), but I'm not sure if that is correct.

class Inheritance {

    private static void println (Object line){
        System.out.println(line.toString());
    }

    static class A {
        public int multiply(int a, int b){
            int val = a*b;
            return val;
        }
    }

    static class B extends A {
        public int multiply(int a, int b) {
            int val = a * b * 5;         
            return val;
        }
    }

    public static void main(String[] args) {
        B b_class = new B();
        b_class.multiply(3,4);

        println(b_class);
        println("Hello World");

    }
}

The output is as follows:

Inheritance$B@74a14482
Hello World
Xeyler
  • 96
  • 9
Praxis
  • 934
  • 2
  • 17
  • 31

3 Answers3

1

For Java toString method default it will

returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()

so when you println b_class it will print: Inheritance$B@74a14482.

For your println (Object line) it's receiving Reference type(Object) to println, but as multiply method it's return a primitive type(int), it's not an object, you need to convert it to an Object for println method, as @StanteyS's answer, use Integer.toString can convert int to String.

What's the difference between primitive and reference types?

Community
  • 1
  • 1
chengpohi
  • 14,064
  • 1
  • 24
  • 42
1

You can just use the method inside println

public static void main(String[] args) {
        B b_class = new B();

        println(Integer.ToString(b_class.multiply(3,4)));
        println("Hello World");

    }
Stanley S
  • 1,052
  • 13
  • 22
1

When you are executing println(b_class); implicitly it calls toString method of same class, which is inherited from Object class.

You need to override toString method to display correct output.

static class B extends A {
  int val=0;
    public int multiply(int a, int b) {
        val = a * b * 5;         
        return val;
    }
  public String toString(){
   return String.valueOf(val); 
   }
}

Now, println(b_class); will work as per your expectation.

Ravi
  • 30,829
  • 42
  • 119
  • 173