3.7 Creating Print Representations For Objects

PrintObject.java

class User {      
    private String name;
    private int age;

    public User( String str, int yy ) { name = str;  age = yy; } 

    public String toString(){                                     //(A)
        return "Name: " + name + " Age: " + age;
    }
}

class Test {
    public static void main( String[] args ) {
        User us = new User( "Zaphod", 119 );
        System.out.println( us );    // Name: Zaphod  Age: 119    //(B)
    }
}

PrintObject.cc

#include <iostream>
#include <string>
using namespace std;

class User {      
    string name;
    int age;
public:
    User( string str, int yy ) { name = str;  age = yy; } 

    friend ostream& operator<<(ostream& os, const User& user) {   //(C)
        os << "Name: " << user.name << " Age: " << user.age << endl;
        return os;
    }
};

int main()
{
    User us( "Zaphod", 119 );
    cout << us << endl;          // Name: Zaphod  Age: 119        //(D)
    return 0;
}


Maintained by John Loomis, last updated 30 Dec 2006