0

So I am trying to figure out how composition (and OOP) works by looking at the example at https://www.geeksforgeeks.org/composition-in-java/ . However when I try run my program I get an output of the address and the memory address. I am trying to get an output of the following sort:

Plot 1 
building area: com.company.Building@2f4d3709

Instead of what I want which would be:

Plot 1
building area: 320m^2

I am not quite sure what is happening here, I am quite new in Java. Any help is greatly appreciated!

Heres the code I am running:

package com.company;

public class Building {
    private String area;

    Building(String area) {
        this.area = area;
    }
}
package com.company;

public class Plot {
    private String name;
    private Building building;

    Plot(Building building){
        this.building = building;
    }

    public Building getListOfBuildings(){
        return building;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPlotName() {
        return this.name;
    }
}
package com.company;

import java.util.Scanner;


public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String name = "Plot 1 ";
        String area = "320m^2";

        Building building = new Building(area);

        // creating composition between building and plot
        Plot plot = new Plot(building);
        plot.setName(name);

        System.out.println( plot.getPlotName() );
        Building bu = plot.getListOfBuildings();
        System.out.println( "building area: " +  bu);

    }
}

0 Answers0