Search code examples
javamethodsreturnreference-type

How to invoke method returning reference type properly?


I was going through the Oracle Java tutorials on the method returning the results of a reference type but had been stuck for quite a few hours. The link is provided here.

https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html

public class Bicycle {

    private int speed = 0;

    public Bicycle(int a) {
        speed = a;
    }

    public static Bicycle seeWhosFastest (Bicycle bicycle1, Bicycle bicycle2) {

        Bicycle fastest = bicycle1;

        if (bicycle1.speed < bicycle2.speed) {
            fastest = bicycle2;
        }

        return fastest;
    }

    public static void main(String[] args) {

        Bicycle firstBicycle = new Bicycle(100);
        Bicycle secondBicycle = new Bicycle(200);

        Bicycle.seeWhosFastest(firstBicycle, secondBicycle);
    }

}

However, I couldn't get it to work as intended. I was hoping to at least print out the bicycle2 object but nothing showed.

Could you guys help me out here thanks in advance.


Solution

  • Considering that your static seeWhosFastest method returns a Bicycle reference type you can write:

    public static void main(String[] args) {
    
            Bicycle firstBicycle = new Bicycle(100);
            Bicycle secondBicycle = new Bicycle(200);
            Bicycle fastestBike = Bicycle.seeWhosFastest(firstBicycle, 
    secondBicycle);
            System.out.println(fastestBike);
    }
    

    In order for this to print something significant you will need to override the toString method from your Bicycle class with something similar to @Makato's example

    EDIT from your comments:

    First add a second member variable to your Bicycle class something like:

    private String reference;
    

    and then add a toString method (also in your Bicycle class)

    public String toString() {
        return reference;
    }
    

    Now update your bicycle constructor to something like

    public Bicycle(int speed, String reference) {
        this.speed = speed;
        this.reference = reference;
    }
    

    Now change your main method as follows:

    public static void main(String[] args) {
    
            Bicycle firstBicycle = new Bicycle(100, "Bicycle1");
            Bicycle secondBicycle = new Bicycle(200, "Bicycle2");
            Bicycle fastestBike = Bicycle.seeWhosFastest(firstBicycle, 
    secondBicycle);
            System.out.println(fastestBike);
    }
    

    And it should work as expected

    Hope this helps