View Subcategory
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
ruby
class Greeter
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

(Greeter.new("world")).greet()
java
class Greeter
{
public Greeter(String whom) { this.whom = whom; }
public void greet() { System.out.printf("Hello, %s\n", whom); }
private String whom;
}

public class Solution381 {
public static void main(String[] args) {
(new Greeter("world")).greet();
}
}
perl
{ package Greeter;
sub new {
my $self = {};
my $type = shift;
$self->{'whom'} = shift;
bless $self, $type;
}

sub greet {
my $self = shift;
print "Hello " . $self->{'whom'} . "!\n";
}
}

my $greeter = Greeter->new("world");
$greeter->greet();
{
package Greeter;

sub new {
my $class = shift;
my $whom = shift or die 'Need a name to greet';
bless \$whom, $class;
}

sub greet {
my $self = shift;
print "Hello $$self!\n";
}
}

my $greeter = Greeter->new("Bob");
$greeter->greet();
groovy
// version using named parameters
class Greeter {
def whom
def greet() { println "Hello, $whom" }
}
new Greeter(whom:'world').greet()
// version using traditional constructor
class Greeter {
private whom
Greeter(whom) { this.whom = whom }
def greet() { println "Hello, $whom" }
}
new Greeter('world').greet()
scala
class Greeter(whom : String) { def greet() = { printf("Hello %s\n", whom) } }

(new Greeter("world!")).greet()
python
class Greeter(object):
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom

Greeter("world").greet()
cpp
class Greeter
{
public:
Greeter(const std::string& whom);
void greet() const;

private:
std::string whom;
};

int main()
{
Greeter* gp = new Greeter("world");
gp->greet();
delete gp;
}

Greeter::Greeter(const std::string& whom) : whom(whom) {}

void Greeter::greet() const
{
std::cout << "Hello, " << whom << std::endl;
}
public ref class Greeter
{
public:
Greeter(String^ whom);
void greet();

private:
initonly String^ whom;
};

int main()
{
(gcnew Greeter(L"world"))->greet();
}

Greeter::Greeter(String^ whom) : whom(whom) {}

void Greeter::greet()
{
Console::WriteLine(L"Hello, {0}", whom);
}
fsharp
type Greeter(whom' : string) =
member this.greet() = printfn "Hello, %s!" whom'

(new Greeter("world")).greet()
type Greeter(whom' : string) =
let whom : string = whom'
member this.greet() = printfn "Hello, %s!" whom

(new Greeter("world")).greet()
type Greeter =
class
val whom : string
new(whom') = { whom = whom' }
member this.greet() = printfn "Hello, %s!" this.whom
end

(new Greeter("world")).greet()
erlang
Greeter = make_greeter("world!"),
Greeter(greet).
ocaml
class greeter message =
object
method greet = print_endline message
end

let o = new greeter "Hello" in
o#greet
csharp
using System;

class Greeter
{
private string name {get;set;}

public void Greet(){
Console.WriteLine("Hello, {0}",name);
}

public Greeter(string name){
this.name = name;
}
}

class Test
{
static void Main()
{
new Greeter("Dante").Greet();
}
}
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.";
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
haskell
data Greeter = Greeter String

class Greets a where
greet :: a -> IO ()

instance Greets Greeter where
greet (Greeter s) = print s

main = greet (Greeter "Hello")
clojure
(defprotocol IGreeter
(greet [this]))

(deftype Greeter [whom]
IGreeter
(greet [this]
(println (str "Hello, " whom))))

(greet (Greeter. "world"))
(defn greeter [whom]
{:whom whom})

(defn greet [g]
(println (str "Hello, " (:whom g))))

(greet (greeter "world"))
fantom
class Greeter
{
private Str whom
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom") }
}

Greeter("world").greet
go
type Greeter struct {
whom string
}

func (g Greeter) greet() {
fmt.Printf("Hello %s\n", g.whom)
}

func main() {
Greeter{"world"}.greet()
}

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
ruby
class Greeter
attr_accessor :whom
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

greeter = Greeter.new("world") ; greeter.greet()

greeter.whom = 'Tommy' ; greeter.greet()
puts "I have just greeted %s" % greeter.whom
java
class Greeter {
private String whom;

public Greeter(String whom) {
this.whom = whom;
}

public String getWhom() {
return whom;
}

public void setWhom(String whom) {
this.whom = whom;
}

public void greet() {
System.out.println("Hello " + whom + "!");
}
}
Greeter greeter = new Greeter("World");
greeter.greet();
greeter.setWhom("Tommy");
greeter.greet();
System.out.println("I have just greeted " + greeter.getWhom() + ".");
perl
package Greeter;
sub new {
my ($class, $whom) = @_;
bless {whom => $whom}, $class;
}
sub whom {
my ($self, $whom) = @_;
if ($whom) { $self->{whom} = $whom; }
else { return $self->{whom} }
}
sub greet {
my ($self) = @_;
my $whom = $self->{whom};
print "Hello, $whom!\n";
}
package main;

my $g = new Greeter ("world");
$g->greet;

$g->whom("Tommy");
$g->greet;
print "I have just greeted " . $g->whom . "\n";
groovy
class Greeter {
def whom
def greet() { println "Hello, $whom!" }
}

greeter = new Greeter(whom:"world"); greeter.greet()

greeter.whom = 'Tommy'; greeter.greet()
println "I have just greeted $greeter.whom"
scala
class Greeter(var whom: String) {
def greet() = println("Hello " + whom + "!")
}

// Is this really a private value with getter and setter methods,
// or just a public mutable value?

val greeter = new Greeter("World")
greeter.greet()
greeter.whom = "Tommy"
greeter.greet()
printf("I have just greeted %s.\n", greeter.whom)
python

class Greeter(object):
_whom = None

def __init__(self, whom):
self._whom = whom

@property
def whom(self):
return self._whom

@propset(whom)
def whom(self, value=None):
self._whom = value

def greet(self):
print 'Helo, %s!' % self._whom

greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
# required for Python 2.5 or less
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper

class Greeter(object):
_whom = None

def __init__(self, whom):
self._whom = whom

@property
def whom(self):
return self._whom

@propset(whom)
def whom(self, value=None):
self._whom = value

def greet(self):
print 'Helo, %s!' % self._whom

greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
cpp
#include <iostream>

using namespace std;

class Greeter {
string whom_;

public:
Greeter(const string &whom) : whom_(whom) {}

string get_whom() const {
return whom_;
}

void set_whom(const string &whom) {
whom_ = whom;
}

void greet() const {
cout << "Hello " << whom_ << "!" << endl;
}
};

int main()
{
Greeter greeter("world");
greeter.greet();
greeter.set_whom("Tommy");
greeter.greet();
cout << "I have just greeted " + greeter.get_whom() << "." << endl;
}
fsharp
type Greeter(name:string) =
let mutable whom = name

member this.Whom
with get () = whom
and set v = whom <- v

member this.Greet() =
printfn "Hello, %s!" whom

let greeter = Greeter("World")
greeter.Greet()
greeter.Whom <- "Tommy"
greeter.Greet()
printfn "I have just greeted %s." greeter.Whom
ocaml
class greeter =
object
val mutable whom = "someone"
method set_whom greetee = whom <- greetee
method get_whom = whom
method greet = Printf.printf "Hello, %s!\n" whom
end;;

let o = new greeter in
o#set_whom "Tommy";
o#greet;
Printf.printf "I have just greeted %s.\n" o#get_whom
csharp
class Greeter
{
public string Name {get;set;}

public void Greet(){
Console.WriteLine("Hello, {0}",Name);
}

public Greeter(string name){
this.Name = name;
}

// Driver
public static void Main()
{
var g = new Greeter("Dante");

g.Name = "Tommy";
g.Greet();
Console.Write("I have just greated {0}", g.Name);
}
}
php
class Greeter {
private $whom;
public function __construct($whom) {
$this->whom = $whom;
}
public function greet() {
echo "Hello $this->whom.\n";
}
public function getWhom() {
return $this->whom;
}
public function setWhom($whom) {
$this->whom = $whom;
}
}
$g = new Greeter("Giacomo Girolamo");
$g->greet();
$g->setWhom("Jean-Jaques");
$g->greet();
echo "I have just greeted " . $g->getWhom() . ".\n";
haskell
data Greeter = G { greeting :: String, greetee :: String }

class Greets a where
greet :: a -> IO ()

instance Greets Greeter where
greet g = print (greeting g)

main = do
let g = G { greeting = "Hello", greetee = "{whom}" }
greet g
print $ "I have just greeted " ++ greetee g { greetee = "Tommy" }
clojure
(defn greeter [whom]
(atom {:whom whom}))

(defn get-whom [g]
(:whom @g))

(defn set-whom [g whom]
(swap! g #(conj % {:whom whom})))

(defn greet [g]
(println (str "Hello, " (:whom @g) "!")))

; using the "class"
(let [g (greeter "world")]
(greet g)
(set-whom g "Tommy")
(greet g)
(println (str "I have just greeted " (get-whom g) ".")))

; or same effect without using any variables
(println (str "I have just greeted "
(get-whom (doto (greeter "world")
(greet)
(set-whom "Tommy")
(greet)))
"."))
fantom
class Greeter
{
new make(Str whom) { this.whom = whom }
Void greet() { echo("Hello, $whom!") }
Str whom
}

greeter := Greeter("world")
greeter.greet
greeter.whom = "Tommy"
echo("I have just greeted ${greeter.whom}.")